How To Use JavaScript Function as Variable

How To Use JavaScript Function as Variable

JavaScript Function can be used as a variable almost everywhere, in assignments, formulas and calculations.

JavaScript Function

A JavaScript function is a section of code made to perform same task repeatedly, so you don't have to write same set of lines again and again. JavaScript Functions make your code reusable.

JavaScript Function Example

function myFunction(a, b) 
{
  return a + b;   // This function returns the sum of a and b
}

This is simple example of JavaScript Function that adds two numbers and return the sum.

JavaScript Function Syntax

JavaScript Function is defined using the keyword function. After that function name is written, followed by parentheses. Inside these parentheses parameters are written, separated by commas. After that, the block of code is written inside the curly brackets.

JavaScript Function as Variable

First consider a simple example of JavaScript Function which calculates the area and returns the result.

We have used simple variables in this code.

function calculateArea(length , width)
{
var area = length * width;
return area;  // function return
}
var area = calculateArea(10 , 5);
var roomArea = "The room area is " + area; // with variable

Now we will use JavaScript Function as a variable. See code example below.

function calculateArea(length , width)
{
var area = length * width;
return area;  // function return
}
var roomArea = "The room area is " + calculateArea(10 , 5); // function being used as a variable

In the above code JavaScript Function calculateArea() is being used as variable in place of variable area. You can also use any JavaScript Function as variable in your code.

How to Change Image on Hover with JavaScript How to Disable Button by Class Name in JavaScript How To Change Image Size with JavaScript How to change Image opacity with JavaScript How to Change image src on click with JavaScript How to get the lang attribute value in JavaScript How to Get attribute Value using JavaScript How To Check if Attribute Exists or not with JavaScript How To Count number of links on Page with JavaScript How To Scroll Page to Bottom using JavaScript How To Detect Shift Key Press with JavaScript Change Text Color On Hover with JavaScript Hide and Show div using JavaScript Get Button text with JavaScript Get textarea value with JavaScript Get table row Height with JavaScript Auto Increase width of input field with JavaScript Set Textarea maxLength with JavaScript Set Textarea Value with JavaScript JavaScript Count list items JavaScript set input field value Count Button Clicks with JavaScript Scroll Page to the Top on Click with JavaScript Change id of Element with JavaScript JavaScript Change li Text Color