Hoisting

What is hoisting?

When a Javascript file is loaded, declarations are moved to the top of the code

 

 

Hoisting Example

console.log(lunch); //undefined
var lunch = 'orange chicken'

//var declaration
var lunch;

//var assignment
lunch = 'orange chicken';

//var declaration and assignment
var lunch = 'orange chicken';

//how JS interepts the order
//only the declaration is hoisted; not the assignment
var lunch;
lunch = 'orange chicken';

Always declare all variables at the beginning of every scope

Function Declarations ​  

  • begins with 'function' and no variable assignment

  • sibling of var declarations

  • are known before any code is run

  • are hoisted to the top

Function Expressions

  • Must not start with 'function'
  • part of a larger expression syntax
  • cannot call a function before it has been expressed
  • are NOT hoisted
function foo(){
 return 'hello';
}

foo();
var bar = function(){
 return 'world';

}

bar()

Function Declarations vs Function Expressions

Function Declarations 

function add(n1, n2){
  return n1 + n2;  
}
console.log(add(1,2)); // logs 3


console.log(subtract(5,3));  // logs 2
function subtract(n1, n2){
  return n1 - n2;
}

Function Expressions 

var add = function(n1, n2){
  return n1 + n2;
}
console.log(add(2, 3)); // logs 5

console.log(subtract(5, 2)); //error
var subtract = function(n1, n2){
  return n1 - n2;
}

Another Hoisting Example

//function declaration
add();
function add(n1, n2){
  return n1 + n2;
}

//How Javascript interepts it:
//function declaration gets hoisted to the top 
function add(n1, n2){
  return n1 + n2;
}
add();

//function expression
subtract()
var subtract = function(n1, n2){
  return n1 - n2;
}

//How Javascript interepts it:
//Only the variable declaration is hoisted to the top
var subtract;
subtract(); //error subtract is not a function
subtract = function(n1, n2){
  return n1 - n2;
}

What will be the result?

//Expression and Declaration
//What is the result of invoking five()?
var five = function(){
  return 5;
}
function five(){
  return 'five'
}
five(); //?

How it is interpeted

//Expression and Declaration
//How will this be interepted?
var five = function(){
  return 5;
}
function five(){
  return 'five'
}
five(); //?



//How the code is interpreted through hoisting
function five(){
  return 'five';
}

var five;
five = function(){
  return 5;
}
five(); // 5
Made with Slides.com