Why does JavaScript hoist variables?
Asked Answered
D

3

144

Why does JavaScript hoist variables?

What was the rationale of the designers when they decided to implement hoisting? Are there any other popular languages that do this?

Please provide relevant links to documentation and/or records.

Dendy answered 21/2, 2013 at 14:45 Comment(17)
“because javascript doesnt really have a true sense of lexical scoping”, whatever that meansGe
Nice! do you know why ?Dendy
I suspect at this point it's historical, and I seriously doubt it was anything other than "ease of implementation" originally.Telephonic
It makes it easier for beginners to pick up the language. Many people write javascript and have no idea about the scope of a variable until they move to another language.Aldredge
perhaps you know of any other language that has a similar characteristic?Dendy
Because without it you can get odd behaviors that are difficult to troubleshootPhylys
@StenPetrov other languages, that are also easy (Python ...) dont hoist!Dendy
Another language that also does this is VBScript.Davison
Honestly, ask Brendan Eich, he seems to be quite responsive.Fleshly
Imagine this ` var a = 0; function a(){ setTimeout(function(){alert(a)},1000) var a = 10; }` when the timeout fires it has access to 'a' because it is in its closure scope, and it makes sense, what should have happened if there would not be hoisting? should it alert 0, because the local was not yet defined, but in the time the timeout fires it is definedAssibilate
How is this question not constructive?Fowlkes
@Fowlkes welcome to Stack Overflow, where all you can ask about is moving a div in jQueryDendy
This is a really important question. It should have been allowed. It was not flame-bait. Hoisting is one of the core elements of understanding how JavaScript works, and the "why" is a legitimate question that is addressed in most textbook treatments of the language. It is NOT OK that Stack Overflow people CONSTANTLY stomp on people's questions like this.Mordecai
I also think that this is an important question. I specifically did a search on why JS hoists variables so that I could leverage its supposed benefits and advantages which so many tutorials claim. I wanted to code JS as it was intended. Indeed, this might be one of the most important questions in JS. Maybe it should have been reworded as, what are benefits of JS variable hoisting.Quaquaversal
@FelixKling Re: Brendan Eich. Asked & awaiting response twitter.com/geraldfullam/status/961621904330248193Pectoralis
Another popular language which has variable hoisting is Python: https://mcmap.net/q/24640/-interactions-between-variable-hoisting-and-other-aspects-of-a-programming-language/2326961Slosberg
See also Is there a purpose to hoisting variables?Encomium
N
67

As Stoyan Stefanov explains in "JavaScript Patterns" book, the hoisting is result of JavaScript interpreter implementation.

The JS code interpretation performed in two passes. During the first pass, the interpreter processes variable and function declarations.

The second pass is the actual code execution step. The interpreter processes function expressions and undeclared variables.

Thus, we can use the "hoisting" concept to describe such behavior.

Northcliffe answered 22/2, 2013 at 0:22 Comment(7)
I personally really do not like the word "hoisting". It gives the false representation that variable and function declarations are magically hoisted to the top of the current scope, when in reality, the JS interpreter, as you mentioned, scans the source code for the bindings and then executes the code.Fevre
Now I got why JS most misunderstood language, I didn't see this in any tutorial. And got confused with hoisting (and interepreter flow).Osmo
Uh, this doesn't really explain the rationale. A single-pass interpreter (that would not have led to hoisting) would have been much simpler - so why did the designers opt for two passes?Encomium
This does not explain why variables, specifically are hoisted. Functions make sense, variables do not (in most cases) -- I believe it's a bug.Extricate
Josh M. This is so extensively specified, I don't think that this is a "bug" ... (I agree that this answer doesnt really answer the reasoning though)Collusion
I've given this a -1 as it doesn't answer the question.Eliathas
This answer doesn't really explain why the designer decides to implement hoisting, just explain what causes hoisting. so I would also give a -1. And as the other answer mentioned by @gfullam, the result of "hoisting" could be unintended.Colander
P
53

JS creator Brendan Eich once said on X (the social media platform formerly known as Twitter)

"var hoisting was thus [an] unintended consequence of function hoisting, no block scope, [and] JS as a 1995 rush job."

He preceded with the explanation that…

"function hoisting allows top-down program decomposition, 'let rec' for free, call before declare; var hoisting tagged along."

Brendan Eich

Are there any other popular languages that do this?

I don't know of any other popular languages that hoist variables in the same manner. I think even ActionScript — another implementation of ECMAScript used in Flash development — did not implement hoisting. This has been a source of confusion and frustration for developers familiar with other languages who are learning JavaScript.

Pectoralis answered 28/1, 2020 at 14:54 Comment(5)
Giving a +1 as this is the only answer that attempts to directly address the question.Lipoprotein
Thank you for this answer. I fully agree with @Damon!Eliathas
Another popular language which has variable hoisting is Python: https://mcmap.net/q/24640/-interactions-between-variable-hoisting-and-other-aspects-of-a-programming-language/2326961Slosberg
Incorrect. Python does NOT have variable hoisting. See: discuss.python.org/t/…Lamprey
Interesting also the followup of that tweet, which explains what "let rec" is twitter.com/BrendanEich/status/1290676504502788096, pointing to #16531034Rhetor
C
3

This is because javascript interpreter interprets code in two cycles.

  1. Code completion/compilation:
  2. Code execution:

In 1st cycle all the variable and function declarations are taken to top of the function scope it is executing in. This helps in creating variableObjects for execution context of function even before it's execution.

In 2nd phase, value assignments, code statements and function calls takes place line by line in expected manner.

You have a little more detailed read over here.

It will give you a better picture around behavior around let, const and class declarations, also the precedence it follows between variable and functions.

Chishima answered 2/3, 2019 at 13:50 Comment(1)
Are you implying that it's a consequence of a design choice? If so, you should state it clearly in your answer. But reading Brendan Eich's answer, it might have been a wanted feature, it depend of how you interpret the last sentence. Bottom line, i still don't know why for sureHepza

© 2022 - 2024 — McMap. All rights reserved.