javascript

Function expressions vs. function declarations in JavaScript

A function declaration loads before any code is executed while a function expression loads only after the interpreter has already reached it.

Below is an example of a function declaration

function declaration() {
    return 10; 
} 

Because function declarations are hoisted, it can be called before or after it is defined without causing an error.

console.log(declaration());

function declaration() {
    return 10; 
} 

// 10 is written to the console

In contrast, below is an example of a function expression

var expression = function() {
    return 10; 
};

Because function expressions will not be hoisted, it can only be called after being reached by the interpreter. The snippet below will cause an error.

console.log(expression());

var expression = function() {
    return 10; 
};

// undefined is written to the console

Waiting to call the function expression until after the interpreter has already reached it fixes the error.

var expression = function() {
    return 10; 
};

console.log(expression());

// 10 is written to the console

more JavaScript posts