ES6+ Features
Destructuring
// Array
const [a, b, ...rest] = [1, 2, 3, 4, 5];
// a=1, b=2, rest=[3,4,5]
// Object
const { name, age, ...other } = { name: "Ajay", age: 25, city: "Delhi" };
// name="Ajay", age=25, other={city:"Delhi"}
// Nested
const { address: { city } } = { address: { city: "Delhi" } };
// Default values
const { role = "user" } = {};
Spread & Rest
// Spread — expand
const arr = [1, 2, 3];
const copy = [...arr, 4, 5]; // [1,2,3,4,5]
const obj = { a: 1 };
const merged = { ...obj, b: 2 }; // {a:1, b:2}
// Rest — collect
function sum(...nums) {
return nums.reduce((a, b) => a + b, 0);
}
Template Literals
const name = "Ajay";
const greeting = `Hello, ${name}!`;
const multiline = `
Line 1
Line 2
`;
// Tagged templates
function highlight(strings, ...values) {
return strings.reduce((acc, str, i) =>
`${acc}${str}<b>${values[i] || ""}</b>`, ""
);
}
Optional Chaining & Nullish Coalescing
const user = { profile: { name: "Ajay" } };
// Optional chaining — stops at null/undefined
user?.profile?.name; // "Ajay"
user?.address?.city; // undefined (no error)
user?.getAge?.(); // undefined (no error if method missing)
// Nullish coalescing — default only for null/undefined
const value = null ?? "default"; // "default"
const zero = 0 ?? "default"; // 0 (not replaced!)
const empty = "" ?? "default"; // "" (not replaced!)
// vs OR operator
const value2 = 0 || "default"; // "default" (0 is falsy)
Modules
// Named exports
export const PI = 3.14;
export function add(a, b) { return a + b; }
// Default export
export default class Calculator {}
// Import
import Calculator, { PI, add } from "./math.js";
import * as Math from "./math.js";
Other Notable Features
// for...of
for (const item of [1, 2, 3]) {}
// Map & Set
const map = new Map([["key", "value"]]);
const set = new Set([1, 2, 3, 3]); // {1, 2, 3}
// Symbol
const id = Symbol("id");
// Generators
function* gen() {
yield 1;
yield 2;
}
// Object shorthand
const name = "Ajay";
const user = { name, greet() { return this.name; } };
Key Takeaways
- Destructuring and spread/rest simplify data manipulation.
- Optional chaining (
?.) prevents errors on nested access. - Nullish coalescing (
??) only defaults fornull/undefined, unlike||. - Modules (
import/export) are the standard for code organization.