What is Javascript Hoisting?

Javascript hoisting is something that happens behind the scenes that oftentimes gives beginners a headache. Hoisting occurs when a browser compiles all of your code and brings all variable and function declarations to the top.

So what does this mean? Well, let’s start with variable hoisting. Take the following code:

someNumber = 3;
var someNumber;

“someNumber” is assigned a value before being declared, so shouldn’t the variable be undefined? Wrong. Due to hoisting, all variable declarations are pushed to the top, so the browser actually reads the code as

var someNumber;
someNumber = 3;

This works the same for function declarations.

myFunc();
function myFunc() {
return 3;
}

“myFunc” can be invoked and return “3” because the function declaration was read first by the browser during runtime, like so…

function myFunc() {
return 3;
}
myFunc();

Something to remember — only declarations are hoisted to the top of their current scope, not assignments! The below code gives an error when “func2” is invoked of “func2 is not a function”.

(function() {
func1();
func2(); //error: func2 is not a function
  function func1() {
return "something";
}
var func2 = function() {
return "something";
}
}());

This is because the browser compiles and reads the code as

(function() {
function func1() {
return "something";
}
var func2;
  func1();
func2();
  func2 = function() {
return "something";
}
}());

The var func2 is hoisted, but not the expression on the right of the equals sign. This is the assignment, and assignments are not hoisted — just declarations.