var, let, const

Peter Chen

2018-02-04

var
VS
let/const

Hoisting

// Var Declarations are hoisted to the top of the function definition.
function varDemo(condition) {
  // var dec;
  
  console.log(dec); // undefined
  if (condition) {
    var dec = "var";  // dec = "var";
    console.log(dec); // var
  } else {
    console.log(dec); // undefined
  }
}

var

Block Bindings

// Let/Const Declarations are Block Bindings.
// They are not hoisted.
function letDemo(condition) {
  console.log(dec); // ReferenceError: dec is not defined
  if (condition) {
    let dec = "var";
    console.log(dec); // var
  } else {
    console.log(dec); // ReferenceError: dec is not defined
  }
}

let/const

Temporal Dead Zone

function TDZDemo(condition) {
  console.log(typeof varDec); // undefined
  var varDec = "var";

  // ReferenceError: can't access lexical declaration `letDec' before initialization
  console.log(typeof letDec);
  let letDec = "let";

  console.log(typeof letInOtherBlock); // undefined
  if (condition) {
    let letInOtherBlock = "letInOtherBlock";
  }
}

No Redeclaration

function demo(){
  var dec = 'var';
  let dec = 'let'; // SyntaxError: redeclaration of var dec
}

function demo2(condition){
  var dec = 'var';
  if(condition){
    // it creates a new variable called dec within the if statement
    let dec = 'let';  
  }
}

let/const

Global Block Bindings

var globalVar = 'var';

console.log(window.globalVar);  // var

let globalLet = 'let';

console.log(window.globalLet);  // undefined

let
VS
const

Initialization

// Initialization
function initialization(){
  const haveInitialConst = 'dec';
  const haveNotIntialConst;  // Uncaught SyntaxError: Missing initializer in const declaration
  
  let haveInitialLet = 'dec';
  let haveNotIntialLet;
}

Reassign

function reassign(){
  const constDec = 'const';
  constDec = 'reassign';  // TypeError: invalid assignment to const `constDec'
  
  let letDec = 'let';
  letDec = 'reassign';
}

value of Objects can modified

function reassignValueInObj(){
  const pet = {
    name: 'Peter'
  };
  
  pet.name = 'Sunny';
  
  console.log(pet.name);  //Sunny
}

const

var let/const
Scope Hoisting Block Bindings(TDZ)
Redeclaration Yes No
Global Yes No

var VS let/const

let const
Initialization Optional Necessary
Reassign Yes No(except value of objects)

let VS const

Reference

Thank You

Made with Slides.com