hoisting

Hoisting

declarations are "hoisted" to the top of the current scope

// a variable declaration
var one;

// a variable assignment
one = "ūnus":

// variable declaration and assignment
var one = "ūnus";

// when this is written
one = "ūnus"; // variable assignment
var one;     // variable declaration

// JavaScript interprets it in this order
var one;     // hoisted to the top
one = "ūnus";

// only the declaration is hoisted
// not the assignment
console.log( two );  // undefined
var two = "duo";

// JavaScript hoists the declaration
var two;
console.log( two );  // undefined
two = "duo";         // assigned

applies to source files

Hoisting

function declaration vs. function expressions

// function declared after it's invoked
three();
function three(){
  return "trēs";
}

// JavaScript interprets in this order
// declaration gets hoisted to the top of the scope
function three(){
  return "trēs";
}
three(); // "trēs"

// assign anonymous function expression to variable four
four();  // "quattuor"
var four = function(){
  return "quattuor";
}

// JavaScript interprets in this order
// variable declaration gets hoisted to the top of the scope
// assignment does not get hoisted
var four;
four();  // Error! four is not a function
four = function(){
  return "quattuor";
}

Hoisting

can cause confusion, understand how JavaScript interprets

// declaration and expression
var five = function(){
  return 5;
}
function five(){
  return "quīnque";
}
five();  // ??

What is the result of invoking five() ?

Hoisting

can cause confusion, understand how JavaScript interprets

// declaration and expression
var five = function(){
  return 5;
}
function five(){
  return "quīnque";
}
five();  // ??

// JavaScript hoists only declarations
function five(){ // functions are hoisted first
  return "quīnque";
}
var five; // hoisted to top of scope
five = function(){ // assignment in original position
  return 5;
}
five();  // 5

Hoisting

By DevLeague Coding Bootcamp