1. let, const and block scoping

let allows you to create declarations which are bound to any block, called block scoping. Instead of using var, which provides function scope, it is recommended to use block scoped variables (let or const) in ES6.

  1. var a = 2;
  2. {
  3. let a = 3;
  4. console.log(a); // 3
  5. let a = 5; // TypeError: Identifier 'a' has already been declared
  6. }
  7. console.log(a); // 2

Another form of block-scoped declaration is the const, which creates constants. In ES6, a const represents a constant reference to a value. In other words, Object‘s and Array‘s contents may change, only the re-assignment of the variable is prevented. Here’s a simple example:

  1. {
  2. const b = 5;
  3. b = 10; // TypeError: Assignment to constant variable
  4. const arr = [5, 6];
  5. arr.push(7);
  6. console.log(arr); // [5,6,7]
  7. arr = 10; // TypeError: Assignment to constant variable
  8. arr[0] = 3; // value is mutable
  9. console.log(arr); // [3,6,7]
  10. }

A few things to keep in mind:

  • Hoisting of let and const vary from the traditional hoisting of variables and functions. Both let and const are hoisted, but cannot be accessed before their declaration, because of Temporal Dead Zone
  • let and const are scoped to the nearest enclosing block.
  • When using const with fixed strings or values, CAPITAL_CASING might be appropriate (ex: const PI = 3.14)
  • const has to be defined with its declaration.
  • Always use const over let, unless you plan on re-assigning the variable.