Tech Junkie Blog: JavaScript Functions: Storing Functions As Values

Monday, July 30, 2018

JavaScript Functions: Storing Functions As Values

JavaScript is a flexible language, and that flexibility extends to functions.  A JavaScript function are not just codes that you reuse and execute.  There are also values, values that you assign to a variable.  In the following example we are going to write a function that will calculate the radius of a circle.  But instead of invoking radius function like a normal function call, we are going to assign to a function to a variable first.

The following is the formula for a radius according to Google

Here is the code to calculate the radius of a circle in JavaScript


        var r = radius;

        function radius(circumference) {
            return circumference / (2 * Math.PI);



The code above returns a value of the radius by dividing the circumference by 2*Math.PI and outputting the result to the console log.  Notice once we assign the function to the radius to variable r, we can use the variable r in place of the function radius.

Here is the result:

No comments:

Post a Comment