Hoisting in JavaScript - Esoteric JS Part 2


Hello 🐝 Today I want to talk about a concept in JavaScript which you should keep in mind because it is one of those “magical” features that might lead to “invisible” bugs.

They could costs you nerves. And Time. But especially a lot of nerves. This concept is called “Hoisting”. So let’s get started 🚀.

Hoisting

“to hoist” means to lift something up. JavaScript does that with a certain type of variable declaration. To be exact: If you declare a variable with var somewhere nested in a function, the declaration is lifted up to the top of the enclosing function.

The “strange” thing about it: The initialization of the variable remains where you wrote it, only the definition moves to the top.

For example:

function hoistingFunction() { // var blub; is hoisted to the top of this function console.log(blub); // => "undefined", but no error var blub = 'blub'; console.log(blub); // => will console.log 'blub' }

So yep. This is the whole concept of hoisting. Is there a way to avoid this idiosynctratic behaviour? – Yep! Read below.

Declaration of variables | constants with let and const

If you would have declared the variable with let or const you would have gotten an actual Reference Error instead of just seeing an undefined.

function hoistingFunction() { // var blub; is hoisted to the top of this function console.log(blub); // => This will throw a Reference Error: "Uncaught ReferenceError: Cannot access 'blub' before initialization" let blub = 'blub'; console.log(blub); }

Last but not least

If you assign a value to an undeclared variable (so you don’t have a var | let | const keyword, only an identifier). The name will automatically be “hoisted” into the global scope – and this is very bug prone. You can enable the strict mode in JavaScript, so you won’t come across this “feature” at all.

The variables will act like global properties with var, but compared with the “normal” global vars, they can be deleted with the delete keyword of JavaScript.

That’s it for today’s post, thanks for reading, hope to see you next time 👋