EN
JavaScript - function declaration vs function expression
0 points
In this article, we would like to show you the difference between function declaration and function expression in JavaScript.
Quick solution:
1. function myFunction() {}
- is a function declaration,
2. var myFunction = function() {}
- is a function expression.
In this section, we present the difference between function declaration and function expression in a practical example.
In this example, myFunction()
is a function declaration and due to hoisting, it is defined whenever the surrounding function or script is executed.
xxxxxxxxxx
1
myFunction(); // Output: Hello World!
2
3
function myFunction() {
4
console.log('Hello World!');
5
}
In this example, myFunction()
is a function expression, that is defined only after reaching this line.
Example 1:
xxxxxxxxxx
1
myFunction(); // Output: Uncaught TypeError: myFunction is not a function
2
3
var myFunction = function() {
4
console.log('Hello World!');
5
};
Example 2:
xxxxxxxxxx
1
myFunction(); // Output: Uncaught ReferenceError: Cannot access 'myFunction' before initialization
2
3
let myFunction = function() {
4
console.log('Hello World!');
5
};