ES2015/ES6

Table of Contents

  1. Variable Scoping
  2. Arrow functions
  3. Classes
  4. Enhanced object literals
  5. Template literals
  6. Destructuring
  7. Default parameters
  8. Rest parameter
  9. Spread Operator
  10. Iterators & For..of
  11. Generators
  12. Modules
  13. Set
  14. Weakset
  15. Map
  16. Weakmap
  17. Unicode
  18. Proxies
  19. Symbols
  20. Promises
  21. Reflect
  22. Binary and Octal
  23. Proper Tail calls
  24. Array find methods

Variable Scoping


Variable scoping defines where in a program a variable can be accessed or used. Both const and let create variables with block-level scope. The let keyword declares a local variable that can be reassigned, meaning it creates a mutable variable.

let age = 35;

if (true) {
  // demonstrates variable shadowing
  // means redeclaring in inner block
  // without affecting the outer one
  let age = 40;
  // inner block "age"
  console.log(age); // 40
}

// outer block "age"
console.log(age);   // 35

const variables work like let variables in terms of block scope, but they cannot be reassigned. In other words, a const declaration establishes a read-only reference to a value. Reassigning a const variable throws an error.

const number = 100;

// Uncaught TypeError: Assignment to constant variable.
number = 200;

Arrow functions


The arrow function provides a more concise syntax for writing function expressions by opting out the function and return keywords using fat arrow (=>) notation.

// Function expression
const multiplyFunc = function(a, b) {
  return a * b;
}
multiplyFunc(2, 5);

// Arrow function
const multiplyArrowFunc = (a, b) => a * b;
multiplyArrowFunc(2, 5);
// 1. Single parameter and single line 
// → No parentheses and no return keyword
const message = name => console.log("Hello, " + name + "!");
message("Saeed"); // Hello, Saeed!

// 2. Multiple parameters
// → Wrap them in parentheses
const multiply = (x, y) => x * y;
console.log(multiply(2, 5)); // 10

//3. Single parameter and multiple statements
const even = number => {
  if(number % 2) console.log("Even");
  else console.log("Odd");
}
even(5); // odd

// 4. Function body with multiple statements
// → Use braces {} and explicit `return` if needed
const divide = (x, y) => {
  if(y > 0) {
    return x / y;
  }
}
console.log(divide(100, 5)); // 20

// 5. No parameters → Use empty parentheses
const greet = () => console.log('Hello World!');
greet(); // Hello World!