Why are JavaScript lifting variables?

Why does JavaScript raise variables?

What was the rationale for the designers when they decided to carry out the upgrade? Are there other popular languages ​​that do this?

Please provide relevant links to documentation and / or records.

+68
javascript hoisting
Feb 21 '13 at 14:45
source share
2 answers

As Stoyan Stefanov explains in Javascript Templates, the rise is a result of the implementation of the JavaScript interpreter.

Interpreting JS code is a two-step process. 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 concept of "lift" to describe this behavior.

+47
Feb 22 '13 at 0:22
source share

This is because the JavaScript interpreter interprets the code in two cycles.

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

In the 1st cycle, all declarations of variables and functions are transferred to the upper part of the region of the function in which they are executed. This helps in creating variableObjects objects for the execution context the function's execution even before it is executed.

At the second stage, assignment of values, code operators, and function calls occur line by line as expected.

You have a slightly more detailed reading here.

This will give you a better idea of ​​the behavior around let , const and class declarations, as well as the priority that follows between a variable and functions.

0
Mar 02 '19 at 13:50
source share



All Articles