Why does JavaScript hoist variables?

Xlaudius picture Xlaudius · Feb 21, 2013 · Viewed 9.5k times · Source

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.

Answer

lxgreen picture lxgreen · Feb 22, 2013

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.