There is no such thing as hoisting. Hoisting is merely a side effect of the compile phase that occurs and the fact that Javascript is lexically scoped. When the compiler comes to the compile phase it puts all variable and function declarations in memory as it figures out the lexical scopes that exists in the program. But there is no hoisting
function or keyword or module. In fact it wasn't even reference in the Ecmascript spec before the es2015 release.
At the end of the day, hoisting is one of those million dollar words we all use, often because its easier to use rather than explain and discuss the compilation process that javascript goes through.
My suggestion would be to either read through the Ecmascript specs, work through a javascript engine source like v8, or read up on Kyle Simpson's work. He wrote a great series called You Don't Know JS.
Hope this helps!
Hoisting is a term you will not find used in any normative specification prose prior to ECMAScript® 2015 Language Specification. Hoisting was thought up as a general way of thinking about how execution contexts (specifically the creation and execution phases) work in JavaScript. However, the concept can be a little confusing at first.
Conceptually, for example, a strict definition of hoisting suggests that variable and function declarations are physically moved to the top of your code, but this is not in fact what happens. Instead, the variable and function declarations are put into memory during the compile phase, but stay exactly where you typed them in your code. <- From the Mozilla docs
https://developer.mozilla.org/en-US/docs/Glossary/Hoisting
JS is a two pass system, it compiles and then executes
that's sort of incorrect. The code could be compiled but that would be implementation dependent. What you are talking about is the JS interpreter parsing the code and then executing it. However, as for usefulness of hoisting...I really can't think of a reason you really need to have it for variables. If you don't hoist, then if you dox = 42; var x
would be an error...which I think is fine. – Enlistmentvar foo = 42; function bar() { console.log(foo); var foo = 21; }; bar();
log42
? Some languages do that... Or should it throw an error? (you get that withlet
andconst
). In the end, it's just one of the decisions one has to make when designing a language. I think it's generally agreed upon that initializing variables withundefined
is sub-optimal, which is why we havelet
andconst
. – These