Hoisting in JavaScript first appeared on Medium.
There are a lot of confusing concepts in JavaScript. As a newbie, hoisting has tripped me up a lot. I got caught up on variable scope crossed my wires somewhere around there. Frankly, the lightbulb didn’t go off until I had my project review. So, let’s talk about this confusing magic!
What is hoisting?
JavaScript defines all variable and function declarations at the top of the scope (even if they are written at the bottom of the scope). These declarations are stored into memory during the compilation phase.
Hoisted ‘var’s are always hoisted as “undefined”, even if you assign a value, because ONLY the declaration moves to the top of the scope. Take this example:
var cat;
console.log(cat);
cat = `parker`;
//undefined
This will console.log “undefined” because we’re assigning cat to ‘parker’ after we console.log, so the variable is initializing after we call it. This is pretty clear. But, take a look at this example. It will return “undefined” as well:
console.log(cat);
var cat = `parker`;
//undefined
Why? Well, it works exactly the same as the first example. Although ‘var cat’ is being hoisted, ‘= parker’ is not, because ONLY the declaration moves to the top.
In yet another example, if we did the following, we’d get “ReferenceError: cat is not defined”:
console.log(cat)
cat = `parker`
// ReferenceError: cat is not defined
When we console.log, JS has no idea what we are talking about, because no hoisting as occurred (cat = ‘parker’ is an initialization).
Here is a working example:
cat = `parker`;
console.log(cat);
var cat;
// parker
This returns “parker,” because the declaration hoists to the top and we define it / call it after it is declared.
Let, Const
Unlike var, let and const don’t hoist as an initialized ‘undefined.’ Check out this example:
console.log(cat)
const cat = `parker`
// Uncaught ReferenceError: Cannot access ‘cat’ before initialization
Whether the above code said ‘const’ or ‘let’, the error would remain the same: “Uncaught ReferenceError: Cannot access ‘cat’ before initialization”
Tip: Always declare your ‘let’ and ‘const’ variables at the top of the scope!
As a new developer, understanding hoisting is key. Without knowledge of how it actually works, you may spend a lot of time debugging code. (I mean, you’ll probably already spend a lot of time debugging code, but you know what I’m saying. Right?)
Top comments (0)