Javascript - Function name as variable


Because function names are pointers to functions, they can act like any other variable pointing to an object.


function sum(num1, num2){
    return num1 + num2;
console.log(sum(10,10));    //20

var anotherSum = sum;
console.log(anotherSum(10,10));  //20

sum = null;/*www .ja  v  a2 s . com*/
console.log(anotherSum(10,10));  //20


This code defines a function named sum() that adds two numbers together.

A variable, anotherSum, is declared and set equal to sum.

Using the function name without parentheses accesses the function pointer instead of executing the function.

At this point, both anotherSum and sum point to the same function, meaning that anotherSum() can be called and a result returned.