Saturday, June 13, 2015

Number of ways in JavaScript to create functions

Functions in JavaScript are first class object, we can add properties in functions as we add in any object of JavaScript. We can pass function as argument in any function as we pass any object or variable. There are 3 ways we can define function in JavaScript.

  1. Function constructor
  2. Function statement
  3. Function expression

1. Function constructor

Create function using Function constructor as shown below, I am creating one simple function for addition of 2 numbers:
var add= new Function('x','y','return (x+y);');
In this type of function creation, last parameter is the function body. we can pass as many parameters we want. In below example I am passing 3 parameters.
var add= new Function('x','y','z','return (x+y+z);');

2. Function statement

This is the very common or we can say general approach to create function in JavaScript and similar to other programming languages.
function add(a,b){
 return (a+b);
}
This approach is very simple and easy to understand for new developer of JavaScript also.

3. Function expression

In this approach function is declared in a variable, it is like one expression in JavaScript.
var add = function(a,b){
 return (a+b);
};
There is one more variation of this approach which is called named function expression. As you noticed in above function there is no name given after function keyword, but can give name also as shown below:
var add= function addFn(a,b){
 return (a+b);
};
We can give any name after function and both codes (expression and named expression) behavior is same.

No comments:

Post a Comment