Explain Hoisting In JavaScript.

Hoisting in JavaScript

As some might not be familiar with the term ‘hoisting’ yet have the relevant experience this question could be asked indirectly

In JavaScript function declarations ( function foo() {} ) and variable declarations ( var bar ) are ‘hoisted’ i.e. are silently moved to the very top of the scope. Consider the following code:

(function() {
    console.log(bar); //returns 'undefined'
    //console.log(baz) // error: baz is not defined
    foo(); // outputs 'aloha' to the console

    //function declaration AND its body is hoisted
    function foo() {
    //variable declaration is hoisted but value assignment stays here
    var bar = 1;
    baz = 2; //defines baz in global scope

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *