Hoisting in Javascript

Quick Note: If you don’t understand anything or have any questions or just want to talk about tech, you can connect with me on Instagram, Facebook or twitter

Hoisting

Source

Hoisting in ES5

Normal Hoisting

Consider this line of code

console.log(shape); // Undefinded 
var shape = "square";
console.log(shape); //Square

This will give us undefined? Why? Because you probably think of that as one statement. But JavaScript actually thinks of it as two statements: var shape; and shape = Square;. The first statement, the declaration, is processed during the compilation phase. The second statement, the assignment, is left in place for the execution phase

Hoisting Inside function

function getShape(condition) {
// shape exists here with a value of undefined
console.log(shape) // OUTPUT : undefined
console.log(shape);
if (condition) {
var shape = "square";
// some other code
return shape;
} else {
// shape exists here with a value of undefined
return false;
}
}

Notice: here the shape exsist even though we declared it inside if conditon

Duplicative Declaration

console.log(shape); // Undefinded 
var shape = "square";
console.log(shape); //Square
var shape = "orange"
console.log(shape); //orange

Notice: Here we are declaring shape even though we have declared it once before

Hoisting in ES6: block-level scoping

Hoisting Inside function

function getShape(condition) {
// shape doesn't exist here
// console.log(shape); => ReferenceError: shape is not defined
if (condition) {
let shape = "square";
// some other code
return shape;
} else {
// shape doesn't exist here as well
return false;
}
}

Notice: Here the shape doesn’t exsist

Duplicative declaration in ES6

console.log(shape); // Undefinded 
var shape = "square";
console.log(shape); //Square
let shape = "orange"
console.log(shape); //orange

Notice: This will throw error saying that SyntaxError: Identifier ‘shape’ has already been declared

Function First

While multiple/duplicate var declarations are effectively ignored, subsequent function declarations do override previous ones.

foo(); // 3
function foo() {
console.log( 1 );
}
var foo = function() {
console.log( 2 );
};
function foo() {
console.log( 3 );
}