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?
"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:
function
), for which a new "scope object" will be created*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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With