Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is hoisting possible in JavaScript?

Tags:

javascript

How does JavaScript perform hoisting if it is an interpreted language. Doesn't interpreted languages execute code from top to bottom line by line. Is there any type of compilation working in the background?

like image 356
amit_raj_39 Avatar asked Aug 29 '16 10:08

amit_raj_39


1 Answers

"Interpreted" does not mean that each line is executed immediately as it is being read. The Javascript interpreter first reads the entire file, a process during which it parses the information into executable code. Hoisting is happening here: between parsing and execution.


In a nutshell and very simplified, hoisting works like this:

  • parser/interpreter reads the source code into an intermediate representation
  • some keywords introduce new scopes (e.g. function), for which a new "scope object" will be created*
  • if during the parsing of a scope the parser encounters a var keyword (or other related keywords), it creates that symbol name on the current scope (with no value/undefined)

* Don't read too much into the word "object" here, it's not Javascript we talk about, but the intermediate language Javascript is being compiled to.

So after this process, you've got some intermediary representation of your source code, in which scopes are defined and local symbol names are reserved on it. That's how variable names are hoisted to "the top" before any code has actually been executed.

like image 106
deceze Avatar answered Oct 13 '22 22:10

deceze