Saturday, December 20, 2014

Function Declaration and Function Expression in JavaScript

Function Declaration

function keyword is the first word in statement then it is a function declaration.
Just as variable declaration must start with "var", function declaration must begin with "function".

function square(x) { // function declaration
return x*x;
}
console.log(square(5)); // 25
view raw gistfile1.js hosted with ❤ by GitHub

Function Expression

function keyword is not the first word in statement then it is a function expression.
function expression can be Anonymous function expression or named function expression

var square = function(x) { // Anonymous function expression
return x*x;
};
console.log(square(5)); // 25
view raw gistfile1.js hosted with ❤ by GitHub

var a = function square(x) { // Named function expression
return x*x;
};
console.log(a(5));
view raw gistfile1.js hosted with ❤ by GitHub

Link 1 - Function Declaration
Link 2 - Anonymous Function Expression
Link 3 - Named Function Expression
 

No comments:

Post a Comment