1

I am reading the excellent Javascript documentation provided by Mozilla, and came across the section relating to Variable Hoisting

Coming from a programming background - this seems absolutely barking mad to me. I cannot possibly understand why such a feature (which could easily lead to logic bugs) - would be introduced into the design of the language.

I can see how function hoisting would be useful (if you wanted to keep all declarations to the bottom of a file - not sure why you'd want to do that though), but variable hoisting seems like absolute madness to me.

Am I missing something here ?

Homunculus Reticulli
  • 65,167
  • 81
  • 216
  • 341
  • Perhaps the fact, that `function/var` declared variables don't have block scope in JS. – Teemu Jan 07 '17 at 10:42
  • 5
    Variable **declarations** are hoisted, not assignments. – Etheryte Jan 07 '17 at 10:43
  • None of the comments so far - have explained WHY this is designed into the language in the first place. It seems bizarre (even the Mozilla documentation describes it as "unusual"). I want to know if there's an engineering reason behind designing this into the language - what does it achieve? – Homunculus Reticulli Jan 07 '17 at 10:51
  • 2
    It takes care of the stupidity of using variable declaration in a loop, for example. Note, that ES6 `let` and `const` have a block scope, and they're not hoisted. – Teemu Jan 07 '17 at 10:53
  • It can be madness... but sometimes, in practice, it is convenient to keep utility function `below the fold` – maioman Jan 07 '17 at 11:03

1 Answers1

-1

Hoisting is not a "feature"; it's a "behavior".

Luckily, you don't need to worry about it at all. You could program in JS for years very happily without knowing anything about it. Many people have.

The only reason for knowing about hoisting is if you want to be a language lawyer. or if you want to pass poorly designed employment tests given by some companies you didn't want to work at anyway.

The only thing you need to be aware of is that you should declare and/or initialize your variables at the top of the function, but you were doing that anyway, right?

Skip over the MDN section on hoisting and go on your merry way. If you run into a book which seems fixated on hoisting (or the "temporal dead zone", for that matter), find another book.

If you really want to know WHY hoisting exists and works as it does, you'd have to go back 20 years into the crevices of someone's mind--a bit of speculation not on-topic on SO.