Sunday, September 25, 2016

Javascript: Function Hoisting

JavaScript makes two passes. During first pass,  js gathers all variable declarations (NOT assignments) and function definitions. In the second pass, js executes the code taking information learned in the first pass into consideration.

// hoisting supported for function definitions
// functions can be called before their definition appears in the file
a();

// hoisting NOT supported for function expressions
// variable b is declared but not assigned to yet
// Error: Uncaught TypeError: b is not a function
// b();

function a(){
    console.log('a');
}

var b = function (){
    console.log('b');
}

b();

Output:
a
b