What is the difference between the function statement and function expression in javascript?
The Function statement declares a function. A declared function can be called any no of times like you can call when it requires. Its like declare it and call it whenever you need.
Javascript Function statement/declaration
The function statement identified by the word function in starting of it. Like below
//function declaration
function greeting()
{
return “Hello”;
}
The keyword function followed by the name is the function name. The above statement function is just declared it's not been used. To call a function you need to call it with the name like below
//calling a function
greeting() // Hello
A function object is getting created when its declared and function statement is hoisted to the top of other code. So you can access it by calling the function before function declaration.
//calling a function
greeting(); // Good moringing
function greeting()
{
return "Good morning";
}
Javascript function expression
A JavaScript function can also be defined using an expression. A function expression can be stored in a variable.
It looks like below:-
//function expression
var sayHi = function()
{
return “Hi”;
};
instead of creating function it’s stored in the variable. It can be created when you call the function with the variable name. So the function should be declared before the function call in function expression. Otherwise, it throws an error saying it's not defined. Where in function declaration which will allow you to call before function declaration statement.
Example:-
//calling function
sayHi();
Function expressions aren’t hoisted, which allows them to retain a copy of the local variables from the scope where they were defined.
Below code will throw an error
//calling function
sayHello();
//function expression
var sayHello = function()
{
return "Hello";
}
The above example executed using chrome browser console.
Quiz
comment the below output of the code
alert(foo());
//function declaration
function foo(){
var bar = function() {
return "Hi";
};
return bar();
var bar = function() {
return "Hello";
};
}