JavaScript Function can be used as a variable almost everywhere, in assignments, formulas and calculations.
Table of Contents
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.