Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does JavaScript hoist variables?

People also ask

Why are variables hoisted in JavaScript?

JavaScript Hoisting refers to the process whereby the interpreter appears to move the declaration of functions, variables or classes to the top of their scope, prior to execution of the code. Hoisting allows functions to be safely used in code before they are declared.

Are JavaScript variables hoisted?

JavaScript Declarations are Hoisted In JavaScript, a variable can be declared after it has been used. In other words; a variable can be used before it has been declared.

Is hoisting a good practice in JavaScript?

But as I said before, you gotta be careful with hoisting since as far as functions are concerned, JS only hoists function declarations and as far as variables are concerned, only the variables declared with var and they have to be initialised. Keep this in mind and you'll be fine.


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.


JS creator Brendan Eich once said (on Twitter):

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

He also explained 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.


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.