JS: Hoisting | JavaScript

JavaScript Hoisting

Consider following two code snippets of JavaScript:

var b; b = true; console.log('b:', b);

and

b = 1; console.log('b:', b); var b;

have same impact and result in terms of execution by JavaScript interpreter, and this is because of Hoisting

In most programming languages, a variable must be declare before use that variable, otherwise there will be an error. JavaScript manages this situation. JavaScript moves the declaration on the top of the respective scope.

Hoisting is only possible with declaration but not the initialization

JavaScript Hoisting and initialization

Hoisting doesn't work in case of initialization along with declaration.

console.log('v:', v); var v = 1; v: undefined

In the code snippet above, since the valriable is declared after the usage but it was also initialed at time of declaraiton, that's why the value in v is undefined.

JavaScript Hoisting priority

Hoisting gives priority to function f() over variables var f.

console.log(f()); f = "f string"; function f() { console.log("called f()"); } console.log(f); called f() f string

f identifer was declared as a var as well as function. The function f() moved to the top but var f remain at its position. In short, following would be the Hoisted code after applying Hoisting by the JavaScript for the above code:

function f() { console.log("called f()"); } console.log(f()); var f; console.log(f);
Please note that var f was decalred before function f but still function given priority no matter what is declared earlier.

Why Hoisting priority to function

This is not always the case that Hoisting gives priority to function f() over variables var f. Consider the following code

console.log(f()); var f; function f() { console.log("called f()"); } console.log(f); called f() f string

f identifer was declared as a var as well as function. function f() moved to the top but var f remain at its position. In short, following would be the Hoisted code after applying Hoisting by the JavaScript for the above code:

function f() { console.log("called f()"); } console.log(f()); var f; console.log(f);

When Hoisting Doesn't Working

JavaScript Hoisting does not working in folllowing cases:

  • Declaration Strict Mode (i.e. below "use strict") not hoisted
  • Declaration with let not hoisted
  • Declaration with const not hoisted

Notes

  1. JavaScript keeps variables and functions declaration before execution at top
  2. Hosting is not possible in Strict Mode i.e. "use strict"
  3. Hosting not applied to the declaration with let or const keywords
  4. Hoisting doesn't work for initialization
  5. Hoisting gives prioirty to function over variables