Function Statement
A Function Statement is also known as a Function Declaration.
function x(){
console.log("x called");
}
x(); // x called
This way of creating a function, using the function keyword followed by the function name and its body, is known as a function statement.
Function Expression
Assigning a function to a variable makes the function act like a value.
var y = function (){
console.log("y called");
}
y();// y called
This is known as Function Expression.
function x(){
console.log("x called");
}
var y = function (){
console.log("y called");
}
x(); //x called
y(); // y called
x();
y();
function x(){
console.log("x called");
}
var y = function (){
console.log("y called");
}
//x called
//TypeError: y is not a function
The main difference between a function statement and a function expression is hoisting.
Look at the code above.In the hoisting phase, during the memory creation phase, JavaScript creates memory for a function (e.g., x(): {...}). However, in the case of a function expression, y is treated like a another variable and is initially assigned undefined. It can only be called after it has been defined in the code.
Anonymous Function
A function without a name is known as an anonymous function. According to the ECMAScript specification, a function statement should always have a name.
function () {
} //SyntaxError: Function statements require a function name.
Anonymous functions are used in places where functions are used as values.
Named Function Expression
It is the same as a function expression, but we must provide a function name.
var y = function greet(){
console.log("y called");
}
y(); //y called
greet(); //ReferenceError: greet is not defined.
First Class Function
First Class Function is also known as First class citizens. The ability of functions to be used as values, passed as arguments to other functions, and returned from functions is known as First Class Function.
var y = function(param1){
return function greet(){
}
}
console.log(y());
//Æ’ greet(){
}
--------------------------------------------------------------------
var y = function(param1) {
console.log(param1);
}
function greet(){
}
y(greet);
//Æ’ greet(){
}
Credits to Akshay Saini.
Top comments (0)