DEV Community

loading...

Recap : Let/Const Var + Scoping & Hoisting

monaye profile image Monaye Win Updated on ・1 min read

Hoisting of let and var without scope
https://jsbin.com/zucehag/5/edit?js,console

console.log(myVar); // undefined
console.log(myLet); // not defined

var myVar; 
let myLet; 

hoisting of let and var with func scope
https://jsbin.com/zucehag/4/edit?js,console

console.log(myVar); // not defined
console.log(myLet); // not defined 

function recap() {
  var myVar; 
  let myLet;  
}

recap();

hoisting of let and var with block scope
https://jsbin.com/zucehag/6/edit?js,console

console.log(myVar); // undefined 
console.log(myLet); // not defined 

if(true) {
  var myVar;
  let myLet;  
}

recap();

block scope
https://jsbin.com/zucehag/8/edit?js,console

// block scope
var myVar = "cat";
let myLet = "dog"; 


if(true) {
  var myVar = "good cat"; 
  let myLet = "good dog"; 
}

console.log(myVar); // good cat 
console.log(myLet); // dog

function scope
https://jsbin.com/zucehag/13/edit?js,console

// Func scope
var myVar = "cat";
let myLet = "dog"; 


function recap() {
  var myVar = "good cat"; // cat 
  let myLet = "good dog"; // dog
}

recap();

console.log(myVar);
console.log(myLet);

simple consequence of using var
https://jsbin.com/zucehag/10/edit?js,console

var DEFAULT_PET = "cat";
var myPet = "dog"; 

function callPet() {
  if(!myPet) {
    var myPet = DEFAULT_PET; 
  }
  return myPet; 
}

console.log('Your pet is : ' + callPet()); // cat 

Discussion (0)

pic
Editor guide