9

I came across an interesting perspective at a recent job interview.

Hoisting in Javascript is about moving the variable declarations and function declaration at the top of the script. Can we call this phase as compilation?

I am aware about the fact that the Javascript interpreter has 2 passes over the input script where in the first pass it does hoisting and the second pass it actually executes the script. Having known that Javascript is an interpreted language, this question got me a bit confused.

18

No. Hoisting is not compilation.

Hoisting is a concept that was created by developers to explain what happens during compilation when variables and function declarations are moved to the top of their containing scope.

Compilation is what happens when your Javascript code is turned into some other representation (usually some kind of executable code), to be executed either now or later. Chrome's V8 Javascript engine actually has two compilers; one to create quick and dirty executable code now, the other to create optimized code later.

Programming languages aren't defined as "compiled" or "interpreted" languages. Rather, languages are interpreted or compiled as needed.

Further Reading
Hoisting in Javascript
How the V8 Engine Works

  • 1
    The wikipedia article on interpreted languages is also helpful on the "interpreted" vs. "compiled" distinction: en.wikipedia.org/wiki/Interpreted_language – user82096 Nov 13 '15 at 7:11
  • If I am understanding this correctly, Hoisting doesn't convert the script to machine readable code, so it is not compilation. Am I right? :) – Rahul Desai Nov 13 '15 at 18:06
  • Read the second paragraph of my answer again. – Robert Harvey Nov 13 '15 at 18:50
  • 1
    In my recent conversation with that interviewer about this topic, he gave me the reference to the Advanced JS course on FrontendMasters.com where Kyle Simpson explains that it is compilation, in the sense that if we compare this to Bash scripting, for instance, it wouldn’t know what to expect on line#4 while it is on line # 3. However, in case of the JS compiler, it has seen what is on line # 4 earlier during the hoisting pass. Its just that it is not converted into binary code unlike other languages. Javascript is compiled everytime it is run. – Rahul Desai Dec 18 '15 at 19:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.