ES6 in Depth
  • Introduction
  • Installation
  • Block Scope
    • Constant
    • Use cases
  • Template String
    • New String Methods
    • Tagged Template Literal
  • New Number Methods
  • Arrow Function
    • Default Parameters
    • Lexical This Scope
    • Where not to use arrow function
  • Object Enhancement
  • New Array Methods
    • For Of
  • Spread Operator
  • Destructuring
    • Array Destructuring
  • Class
  • Symbols
  • New Data Structures
    • Set
    • Map
    • WeakSet
    • WeakMap
    • Iterators
    • Generators
  • Promise
  • Import Export
Powered by GitBook
On this page
  • Temporal dead zone ( cann't access variable before it's defined)
  • Example
  • ES5
  • ES6 (using let)

Was this helpful?

Block Scope

// ES5
var x = 12;

if( x< 15){
  var msg = 'Quantity is small';
}

console.log(msg); // Quantity is small

// ES6
let x = 12;

if(x< 15){
  let msg = 'Quantity is small';
}

console.log(msg); // ReferenceError: msg is not defined

Temporal dead zone ( cann't access variable before it's defined)

console.log(myVar); // "ReferenceError: myVar is not defined
let myVar = 10;

Example

ES5

var arr = [];

for( var i =0; i < 10; i++){
  arr.push(function(){
    console.log(i);
  });
}

arr.forEach(function(fn){
  fn(); // (10) 10 // printed 10 times
});

ES6 (using let)

var arr = [];

for( let i =0; i < 10; i++){
  arr.push(function(){
    console.log(i);
  });
}

arr.forEach(function(fn){
  fn();
});

// output
0
1
2
3
4
5
6
7
8
9
PreviousInstallationNextConstant

Last updated 4 years ago

Was this helpful?