Programming Examples

Are you a Programmer or Application Developer or a DBA? Take a cup of coffee, sit back and spend few minutes here :)

JavaScript 011 – Function Variable

1. Function Variable

In JavaScript, we can store a function in a variable and then call the function using the variable. The variable which stores the function is called Function Variable. This will help passing functions as parameter to other functions. In this example, we will see how to use function as a variable.

2. Calling Function Variable

Now, let us see how to store a function in a variable and then use that variable as a function. Have a look at the below example:

Function as Variable
Function as Variable

1) Here, we created a function SayHello which accepts a person’s name and greets him/her.
2) The variable fnHello stores the function SayHello. The variable is nothing but a complete function.
3) Shows you how we can call a function by its name. Here, we passed Philip as an argument.
4) You can see how we use Function Variable fnHello to call the function SayHello. Here, we passed Priyanka as an argument.

The above example indicates how a function can be assigned to a variable and how the variable can be used later to make a function call.

3. Function Variable as Parameter

In the last section, we saw how to assign a function to a variable. Now, we will see how to pass a function as a variable to some other function. Have a look at the below example:

Function passed as Parameter
Function passed as Parameter

1) Here, we have two JavaScript functions, and they take two params. Both the functions perform math operation and prints the result.
2) DoMath is also a function taking three params. First param is a JavaScript Function. Second and third are params for the math operations & they are operands. In the body, we call the first param as it is a function and pass the two operands on it. These two operands are coming as second and third parameter.
3) We call the DoMath twice. First time we pass, Add function as a parameter. Second time, we pass Multiply function as a parameter. Both the times, we pass operands as 10,10.
4) Shows the result of a function call DoMath. First Call gave the result as 20 as the passed-in first param is an Add function. Second time the result is 100 as DoMath invokes Multiply function.

4. Code Reference

Categories: JavaScript

Tags: , ,

Do you like this Example? Please comment about it for others!!

This site uses Akismet to reduce spam. Learn how your comment data is processed.