Understanding Hoisting in JavaScript

This won’t be a thorough exposition. You can find a great deal of information on GitHub. What I want to do is give the basics.

The JavaScript Interpreter

There are parts to the JavaScript compiler you’d need to understand to get a grip on what happens when a variable is hoisted or lifted to the top of a scope.

There are three parts to the compiler:

The Engine

Compiler

Scope

Looking at this statement: var b = 10, you’re probably assuming this is one statement, and that the JavaScript interpreter sees it the same way. It doesn’t.

The interpreter takes this statement and breaks it up into what are called tokens. To the interpreter, this statement and its tokens are var, b, =, and 10.

The engine part of the interpreter will compile these tokens into an array and subsequent tree of nested elements to execute. The code is compiled right before it is executed.

What is Meant by Hoisting?

I am assuming here that you know what scope is, as I have talked about block scoping before with the same assumption. If you don’t, I’ll cover it in more detail another time. For now, I am just going to focus on hoisting.