DEV Community

adebomiolusegun
adebomiolusegun

Posted on

Function declaration and Function Expression

The function expression is nearly similar to the function declaration, but there are some differences.

The function declaration is created by first declaring the function keyword, followed by a code block where we put our code to be executed.

Function name(parameters){
  Our code to be executed 
}

name(argument);
Enter fullscreen mode Exit fullscreen mode

And meanwhile, the function expression can be stored in a variable, which is then used as a function.

Const name = function ( parameters a, parameter b){

 Our code to be executed 
};

name(argument);
Enter fullscreen mode Exit fullscreen mode

As an expression, the semicolon is placed at the end of the code block because that is where it is expected to be.

Hoisting

hoisting allows you to use functions and variables before they are declared.

This is done with function declaration but not with function expression.

Examples

name(argument);

Function name(parameters){
  Our code to be executed 
}
Enter fullscreen mode Exit fullscreen mode

This is a function declaration; the code will be executed because JavaScript hoisting accepts it.

name(argument);

Const name = function ( parameters a, parameter b){

 Our code to be executed 
};
Enter fullscreen mode Exit fullscreen mode

Meanwhile, because this is a function expression, the code will not run because JavaScript hoisting does not accept it.
It’s will display undefined.

I hope this is of great assistance to someone out there.

Top comments (7)

Collapse
 
nguyentientung51056 profile image
NguyenTienTung51056

good man

Collapse
 
jesamomini profile image
Jesamomini

Well explained

Collapse
 
adebomiolusegun profile image
adebomiolusegun

Thank you!

Collapse
 
michthebrandofficial profile image
michTheBrandofficial

One question. Will the function expression be hoisted if I use the 'var' keyword instead of 'const'.

Collapse
 
michthebrandofficial profile image
michTheBrandofficial

*?

Collapse
 
adebomiolusegun profile image
adebomiolusegun

Function expression cannot be hoisted

Thread Thread
 
michthebrandofficial profile image
michTheBrandofficial

Thank you for the answer.