JS — Hoisting

Hoisting is JavaScript’s default behavior of moving declarations to the top.

“Only declarations are hoisted”

That’s why we can use things before declaring:

// function declaration hoisting
sayHello();  // This works perfectly fine
function sayHello() { ... }

Or this:

// varaible declaration hoisting
console.log(name); // output: undefined
var name = 'naruto';
console.log(name); // 'naruto'

Because Js read it as:

var name;
console.log(name); // undefined
name = 'naruto';
console.log(name); // 'naruto'

Note: this is different from NOT declaring at all. You’ll get an ‘not defined’ error otherwise:

console.log(name); // output: ReferenceError: name is not defined

“Function expression and variable initialization are NOT hoisted!”

sayHello(); // TypeError: undefined is not a function
var sayHello = function() { ... }

Because JS read it as :

var sayHello;
sayHello();
sayHello = function() { ... }

When you use function expression NOTHING will be hoisted:

greeting(); // TypeError: undefined is not a function
sayHello(); // ReferenceError: sayHello is not defined
var greeting = function sayHello() { ... }

Exercise:

var name = 'global';
(function() {
    console.log(name); // output: undefined
    var name = 'local';
    console.log(name); // output: 'local'
})();

Because:

var name = 'global';
(function() {

var name; // hoisted to top of current scope. (global var get shadowed)
    console.log(name); // undefined
    name = 'local';
    console.log(name); // 'local'
})();

Reference: