Abstract

A thorough overview of ES6

Table of Contents

01 - var scoping refresher

var variables are reassignable. You can also use var twice for the same variable name in the same scope. var variables are function scoped and if they’re not in a function then they are globally available. var variables leak to the global scope fairly easily.

let is block scoped which protects the global scope.

var age = 100;
if (age > 12) {
  const dogYears2 = 79; 
  let dogYears = 7; 
  var foobar = 3;
  console.log(dogYears2);  // result is 79
  console.log(dogYears);  // result is 7
  console.log(foobar);  // result is 3
}

console.log(dogYears2);  // variable is undefined because dogYears2 is block scoped
console.log(dogYears);  // variable is undefined because dogYears is block scoped
console.log(foobar);  // result is 3.  It affected the global scope

02 - let vs const

Using let and const you can only declare them once in the same scope.

let winner = false;
if (true) {
  let winner = true;
}

console.log(winner);  // winner is false because the winner inside of the if and outside are two different variables
let winner = false;
if (true) {
  winner = true;
}

console.log(winner);  // winner is true because the winner inside of the if updated the winner outside of it