ES2015/ES6
Table of Contents
- Variable Scoping
- Arrow functions
- Classes
- Enhanced object literals
- Template literals
- Destructuring
- Default parameters
- Rest parameter
- Spread Operator
- Iterators & For..of
- Generators
- Modules
- Set
- Weakset
- Map
- Weakmap
- Unicode
- Proxies
- Symbols
- Promises
- Reflect
- Binary and Octal
- Proper Tail calls
- 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!