Javascript - Function Declarations versus Function Expressions


Function declarations are processed in an execution context before any code is executed, whereas function expressions aren't complete until the execution reaches that line of code.

Consider the following:

function sum(num1, num2){
    return num1 + num2;

This code runs without error, since function declarations are process to the execution context before the code begins running.

The process is called function declaration hoisting.

As the code is being evaluated, the JavaScript engine does a first pass for function declarations and pulls them to the top of the source tree.

Changing the function declaration to an equivalent function expression will cause an error during execution:

var sum = function(num1, num2){
    return num1 + num2;

This updated code will cause an error, because the function is part of an initialization statement, not part of a function declaration.

The function isn't available in the variable sum in the console.log() method, the first line causes an "unexpected identifier" error.