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.

Get Heading Text using JavaScript Current Date in mm/dd/yyyy Format JavaScript Current Date in dd/mm/yyyy Format in JavaScript JavaScript Current Date in yyyy-mm-dd Format JavaScript Get Date Difference in Hours JavaScript Get Date Difference in Minutes JavaScript Get Date Difference in Seconds Get Last Character of String with JavaScript Trigger Button Click On Page Load JavaScript Get id Of Child Element JavaScript Get Id Of Parent Element in JavaScript Get Table Row Index onclick in JavaScript Remove specific option from Select Tag with JavaScript Change Selected Option of Select Tag with JavaScript Get Length of Text In Textarea with JavaScript Change Text Color of Select Tag Option using JavaScript Change Heading Text in JavaScript Get Input Value Length in JavaScript Toggle Button Text with JavaScript Change Background Color of Dropdown with Dropdown using JavaScript Emoji Mood Slider with HTML CSS and JavaScript Hide and Show Div with Radio Button using JavaScript Count Options In Select Tag with JavaScript Get Select Tag Text OnChange with JavaScript Change Background Color OnClick using Input Field