⚡ Lesson 16 of 30
ES6+ Modern Features
Leverage destructuring, spread/rest, optional chaining, nullish coalescing, and more modern syntax.
Destructuring Arrays
const [first, second, ...rest] = [10, 20, 30, 40, 50];
console.log(first); // 10
console.log(second); // 20
console.log(rest); // [30,40,50]
// Swap variables
let a = 1, b = 2;
[a, b] = [b, a];
console.log(a, b); // 2 1
Destructuring Objects
const user = { id:1, name:"Alice", role:"admin" };
const { id, name, role = "user" } = user;
console.log(id, name, role); // 1 Alice admin
// In function parameters
function display({ name, role }) {
console.log(`${name} is ${role}`);
}
display(user);
Spread Operator
const a = [1, 2, 3];
const b = [4, 5, 6];
const combined = [...a, ...b]; // [1,2,3,4,5,6]
const base = { x:1, y:2 };
const extended = { ...base, z:3, x:99 }; // {x:99,y:2,z:3}
Tagged Template Literals
A powerful feature for building DSLs, safe SQL, styled components, etc.:
function highlight(strings, ...values) {
return strings.reduce((result, str, i) =>
result + str + (values[i] !== undefined
? `${values[i]}` : ""), "");
}
const name = "World";
console.log(highlight`Hello ${name}! Score: ${42}`);
// Hello World! Score: 42
Logical Assignment Operators
ES2021 added three concise logical assignment operators:
let a = null;
a ??= "default"; // a = "default" (only if null/undefined)
let b = 0;
b ||= 10; // b = 10 (only if falsy)
let c = 5;
c &&= c * 2; // c = 10 (only if truthy)