JavaScript & Hoisting Made Easy

JavaScript & Hoisting Made Easy

Before the parser reads a single line, JavaScript creates all the memory necessary to run our code. Here's how.

Most programming languages execute their code one line at a time. JavaScript is different, however.

Review the following code.

// Example A
var a = 'Hello';

function b (){
    console.log('Called b!');
};

b();
console.log(a);

By running the above code, we see Called b! and Hello logged to the console, which makes sense.

Let's move our function calls to the top of our code. What do we expect to happen now?

// Example B
b();
console.log(a);

var a = 'Hello';

function b (){
    console.log('Called b!');
};

By running the above code, we see Called b! and undefined logged to the console. Notice how no errors are thrown.

Often times, we receive the impression that JavaScript "hoists", or moves functions up to the top, before running our code. But what happens if we remove var a = 'hello'; from our code entirely?

// Example B
b();
console.log(a);

function b (){
    console.log('Called b!');
};

We see our function execute, but we also see an error being thrown as variable a is never defined. So what's going on?

The Creation Phase

Execution contexts are created in two phases. In the first phase...

  • The Global Object is created in memory
  • 'this' is created in memory
  • An 'Outer Environment' is created in memory

After the above is created, the parser begins to set up what we've written for translation to the computer. Part of this involves taking note of where we've created functions and variables.

Our code isn't actually moved to the top. Before our code is read, line by line, JavaScript creates memory space to accomodate for our code's functions and variables. Functions and variables literally begin to "exist" in memory.

The Execution Phase

After the creation phase is complete, JavaScript stores functions, in their entirety, in memory. But JavaScript doesn't know what variable values will be just yet.

JavaScript sees var a, and sets the value to undefined. In fact, ALL variables are set to undefined when code is first executed.

This is why logging a to the console before we declare var a = 'Hello' results in ``undefined, and logginga``` while not declaring anything at all results in an error being thrown.