Javascript Hoisting

Dec. 30, 2020

Scope in Javascript is just one of those things that already seems weird enough, hoisting on top of that sometimes makes my brain melt. The MDN documentation explains it well. Life’s a lot easier if you use const/let instead.

Otherwise, however, I find working through how the compiled code might “look” helpful for understanding what’s going on.

Some quick info that you should know and be familiar with first:

So let’s grab an example from MDN.

// Example 1
// Only y is hoisted

x = 1; // Initialize x, and if not already declared, declare it - but no hoisting as there is no var in the statement.
console.log(x + " " + y); // '1 undefined'
// This prints value of y as undefined as JavaScript only hoists declarations
var y = 2; // Declare and Initialize y
// Example 1 - Translated
var y = undefined;

x = 1;
console.log(x + " " + y); // '1 undefined'
y = 2;

Let’s do something a little more complicated and make console log occur from a function and do some tweaking in there.

// Original
var x = 1;
var y = 2;
var z = 3;

function exec() {
  console.log(x + " " + y + " " + z);
  var y = -1;
  z += 1;
}

exec(); // '1 undefined 3'
exec(); // '1 undefined 4'
// Translated
var x = 1;
var y = 2;
var z = 3;

function exec() {
  var y = undefined;
  console.log(x + " " + y + " " + z);
  y = -1; // (local due to var)
  z += 1; // (global)
}

exec(); // '1 undefined 3'
exec(); // '1 undefined 4'