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.

JavaScript Hide Button After Click Simple Click and Hold Effect Using JavaScript JavaScript Select All HTML Elements Whose ID Start With Same String Count Checked Checkboxes of Specific Form with JavaScript Enable and Disable Button using JavaScript Add Class to HTML Tag On Click using JavaScript Change Class of HTML Tag Using JavaScript Get All Options In Select Tag using JavaScript Replace a Word from everywhere in a String using JavaScript Execute a Function on Hover Using JavaScript Open Select File Dialog Box Using JavaScript Display Message When File Is Selected Using JavaScript Get Clicked HTML Element Name Using JavaScript Get Class of Clicked Element Using JavaScript Count Number of Rows in Table using JavaScript Move Background Image with Mouse Using JavaScript Disable Text Selection Using JavaScript Get Selected Radio Button Value On Click using JavaScript Get input Element Value On Click Using JavaScript Toggle Text of HTML Element with JavaScript onclick