Function expression and Anonymous Function expression – Functional Programming in Javascript Part 1

tn500w_javascript-logo

Function expression and Anonymous Function expression – Functional Programming in Javascript Part 1

Most of us know how to create a function using function declaration in javascript.

function hello(){
//some code
}

To execute above function we just need to call the function by writing hello().

What if I say that javascript provides flexibility in creating functions using another approach called function expression. Remember, functions in javascript are first class values, or in simple way functions are values in javascript(its different from functions returning values) And, likewise a value can be assigned to a variable, similarly function can also be assigned to a variable.

var fn = function foo(){
//some code
};

Here, we have assigned a function foo(as value) to variable fn. Note, we are not executing the function foo and returning anything(don’t get confused). fn variable just contains function foo inside it(or, we can say inline function). Now we can use the variable fn to execute the function foo. fn variable actually holds the string representation of function foo.

fn();

Using above statement we executed function foo. Javascript interpreter sees fn as a variable and when it encounters (), it got to know that fn needs to be executed as a function, interpreter will then check if the value of the variable is a function instance. And, yes its a function, and then its happily executed.

You must be wondering that name of function i.e. foo was never used above. Well the fact is it’s never used. So, yes we can also say that function name foo is not required.

var fn = function(){
//some code
};

This kind of expression is called anonymous function expression, i.e. a function which doesn’t have a name and is assigned to a variable. This kind of function expression is mostly used.

About Anoop Kumar Rai