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.
Practical example
In this section, we present the difference between function declaration and function expression in a practical example.
1. function declaration
In this example, myFunction() is a function declaration and due to hoisting, it is defined whenever the surrounding function or script is executed.
// ONLINE-RUNNER:browser;
myFunction(); // Output: Hello World!
function myFunction() {
console.log('Hello World!');
}
2 function expression
In this example, myFunction() is a function expression, that is defined only after reaching this line.
Example 1:
// ONLINE-RUNNER:browser;
myFunction(); // Output: Uncaught TypeError: myFunction is not a function
var myFunction = function() {
console.log('Hello World!');
};
Example 2:
// ONLINE-RUNNER:browser;
myFunction(); // Output: Uncaught ReferenceError: Cannot access 'myFunction' before initialization
let myFunction = function() {
console.log('Hello World!');
};