DEV Community

Dan-Vy Le
Dan-Vy Le

Posted on

JavaScript Fundamentals 101 - Hoisting

alt text

TL;DR

Always declare your variables at the top at the beginning of every scope, then you won't have to deal with the bugs that may come from not understanding "hoisting"

TL;But still going to read

Hoisting is JavaScript's default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function).

Important to remember

let and const CANNOT be hoisted.

Declaration vs. Initialization

var arnold = "2 cats";
//You can declare and initialize in the same line like above

var arnold
// is a declaration

= "2 cats";
// is the initialization of var arnold

When a declaration gets hoisted, but initialization does not:


var arnold = "2 cats";  

console.log("Arnold has " + arnold + " and pumping them " + pumping);
// pumping is hoisted, as a declaration
// it exists, but the initialized value, won't get hoisted

var pumping = "up";

"Arnold has 2 cats and pumping them undefined"
// output

Another example to reinforce:


var arnold = "2 cats";  
pumping = "up";

console.log("Arnold has " + arnold + " and pumping them " + pumping);
// pumping has already been declared

var pumping = "down";


"Arnold has 2 cats and pumping them up"
// output

If you were expecting "Arnold has 2 cats and pumping them down", remember initializations don't get hoisted!

Hope you learned a thing or two about hoisting today!


sources:
https://www.w3schools.com/js/js_hoisting.asp

Top comments (0)