Last Updated: September 09, 2019
·
589
· gerardsans

JavaScript variable and function hoisting

Sons of JavaScript Collection | this article

Hoisting is just another bit of JavaScript that may left some people perplexed. Let's sort that out.

There are mainly two cases of hoisting: variable and function hoisting.

Variable hoisting (regular object)

JavaScript scope is function based so when you declare a local variable using the keyword var it creates an implicit initialisation on the top setting the variable to undefined.

var name = "John"; //local variable within global scope
surname = "Maria"; //global variable within global scope

function Fn() {
  console.log(name); // John
  console.log(surname); // Maria
}

function Fn2() {
  //implicit top declaration: var name; 
  console.log(name); // undefined
  console.log(surname); // Maria
  var name = "Richard"; //local variable within function scope Fn2
  console.log(name); // Richard
}

Fn(); Fn2();

Variable hoisting (reference to a function)

The same behaviour happens when the variable references a function.

function Fn() {
    console.log(myFunction()); //error as myFunction is undefined
    var myFunction = function() {return 1;};
    console.log(myFunction()); // 1
}
Fn();

Function hoisting

Function hoisting works completely different. JavaScript makes available all the functions at the top regardless when they are defined.

console.log(Fn());  // 1
function Fn() {return 1;};
console.log(Fn());  // 1

Sons of JavaScript Collection | this article