What are ES2015 - ES6 features?

1. Block-Scoped Variables: let and const

  • let: Allows block-scoped variable declarations.
  • const: Allows block-scoped constant declarations.

2. Arrow Functions

Concise syntax for functions

3. Template Literals

Use backticks (`) for multi-line strings and string interpolation.

const name = "John";
const message = `Hello, ${name}!`; // String interpolation
console.log(message); // "Hello, John!"

4. Default Parameters

Provide default values for function parameters.

function greet(name = "Guest") {
return `Hello, ${name}!`;
}

console.log(greet()); // "Hello, Guest!"

5. Destructuring Assignment

Extract values from arrays or properties from objects into variables.

// Array destructuring
const [a, b] = [1, 2];
console.log(a, b); // 1, 2

// Object destructuring
const { name, age } = { name: "Alice", age: 25 };
console.log(name, age); // "Alice", 25

6. Spread and Rest Operators

  • Spread (...): Expands arrays or objects.
  • Rest (...): Condenses multiple elements into a single array.
// Spread
const arr1 = [1, 2];
const arr2 = [...arr1, 3, 4]; // [1, 2, 3, 4]

// Rest
const [first, ...rest] = [1, 2, 3]; // first: 1, rest: [2, 3]

7. Classes

Simplified syntax for object-oriented programming.

class Person {
constructor(name) {
this.name = name;
}

greet() {
return `Hello, ${this.name}!`;
}
}

const john = new Person("John");
console.log(john.greet()); // "Hello, John!"

8. Modules (import and export)

Support for modular programming with import and export.

// file.js
export const greet = () => "Hello!";

// main.js
import { greet } from "./file.js";
console.log(greet());

9. Promises

Simplifies handling asynchronous operations.

const fetchData = () =>
new Promise((resolve, reject) => {
setTimeout(() => resolve("Data fetched"), 1000);
});

fetchData().then(data => console.log(data)); // "Data fetched"

10. Enhanced Object Literals

Shorthand for defining properties and methods.

const age = 25;
const person = {
name: "John",
age, // Property shorthand
greet() {
return "Hi!"; // Method shorthand
}
};

11. Iterators and For-Of Loop

for...of simplifies iteration over iterable objects like arrays.

const array = [10, 20, 30];
for (const value of array) {
console.log(value);
}

12. Map and Set

  • Map: Key-value pairs.
  • Set: Unique values.
const map = new Map();
map.set("key", "value");

const set = new Set([1, 2, 3, 1]);
console.log(set); // Set { 1, 2, 3 }

13. Symbol

A new primitive type for unique values.

const sym1 = Symbol("desc");
console.log(typeof sym1); // "symbol"

14. Generators

Functions that can pause and resume execution.

function* generator() {
yield 1;
yield 2;
}
const gen = generator();
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2

15. WeakMap and WeakSet

Similar to Map and Set, but with weak references to keys.