// Array destructuring
const numbers = [1, 2, 3, 4, 5];
const [first, second] = numbers;
console.log(first, second); // 1 2
// Skip elements
const [a, , c] = numbers;
console.log(a, c); // 1 3
// Rest operator in destructuring
const [head, ...tail] = numbers;
console.log(head); // 1
console.log(tail); // [2, 3, 4, 5]
// Default values
const [x, y, z = 0] = [1, 2];
console.log(z); // 0
// Swapping variables
let p = 1, q = 2;
[p, q] = [q, p];
console.log(p, q); // 2 1
// Object destructuring
const user = {
name: 'Alice',
age: 30,
email: 'alice@example.com',
address: {
city: 'New York',
country: 'USA'
}
};
const { name, age } = user;
console.log(name, age); // Alice 30
// Rename variables
const { name: userName, age: userAge } = user;
console.log(userName, userAge); // Alice 30
// Default values
const { role = 'user' } = user;
console.log(role); // 'user'
// Nested destructuring
const { address: { city, country } } = user;
console.log(city, country); // New York USA
// Rest in objects
const { name: n, ...rest } = user;
console.log(rest); // { age: 30, email: '...', address: {...} }
// Function parameter destructuring
function greet({ name, age }) {
console.log(`Hello ${name}, you are ${age} years old`);
}
greet(user);
// Array parameter destructuring
function sum([a, b]) {
return a + b;
}
console.log(sum([5, 3])); // 8
// Spread operator - Arrays
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
// Merge arrays
const merged = [...arr1, ...arr2];
console.log(merged); // [1, 2, 3, 4, 5, 6]
// Copy array
const copy = [...arr1];
// Add elements
const extended = [...arr1, 4, 5];
console.log(extended); // [1, 2, 3, 4, 5]
// Math functions
const nums = [5, 2, 9, 1, 7];
console.log(Math.max(...nums)); // 9
console.log(Math.min(...nums)); // 1
// Spread operator - Objects
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
// Merge objects
const mergedObj = { ...obj1, ...obj2 };
console.log(mergedObj); // { a: 1, b: 2, c: 3, d: 4 }
// Override properties
const updated = { ...obj1, b: 99 };
console.log(updated); // { a: 1, b: 99 }
// Clone object (shallow)
const clone = { ...user };
// Add properties
const enhanced = { ...user, role: 'admin', verified: true };
// Rest parameters in functions
function multiply(multiplier, ...numbers) {
return numbers.map(n => n * multiplier);
}
console.log(multiply(2, 1, 2, 3, 4)); // [2, 4, 6, 8]
// Template literals
const firstName = 'John';
const lastName = 'Doe';
// String interpolation
const fullName = `${firstName} ${lastName}`;
console.log(fullName); // John Doe
// Expressions in templates
const a1 = 5, b1 = 10;
console.log(`Sum: ${a1 + b1}`); // Sum: 15
// Multi-line strings
const message = `
This is a multi-line string.
It preserves line breaks.
No need for \\n!
`;
// Nested templates
const items = ['apple', 'banana'];
const list = `
<ul>
${items.map(item => `<li>${item}</li>`).join('')}
</ul>
`;
// Tagged template literals
function highlight(strings, ...values) {
return strings.reduce((result, str, i) => {
return `${result}${str}<strong>${values[i] || ''}</strong>`;
}, '');
}
const product = 'laptop';
const price = 999;
const ad = highlight`Buy a ${product} for only $${price}!`;
console.log(ad);
// "Buy a <strong>laptop</strong> for only $<strong>999</strong>!"
// Default parameters
function greetUser(name = 'Guest', greeting = 'Hello') {
return `${greeting}, ${name}!`;
}
console.log(greetUser()); // Hello, Guest!
console.log(greetUser('Alice')); // Hello, Alice!
console.log(greetUser('Bob', 'Hi')); // Hi, Bob!
// Arrow functions
const add = (a, b) => a + b;
const square = x => x * x;
const log = () => console.log('Hello');
// Arrow function with object return
const makePerson = (name, age) => ({ name, age });
console.log(makePerson('Alice', 30)); // { name: 'Alice', age: 30 }
// Short property names
const name2 = 'Alice';
const age2 = 30;
const person = { name2, age2 };
console.log(person); // { name2: 'Alice', age2: 30 }
// Computed property names
const key = 'dynamicKey';
const obj = {
[key]: 'value',
[`${key}2`]: 'value2'
};
console.log(obj); // { dynamicKey: 'value', dynamicKey2: 'value2' }
// Method shorthand
const calculator = {
add(a, b) { return a + b; },
subtract(a, b) { return a - b; }
};
// Combining features
function processUsers({ users, filter = () => true, limit = 10 }) {
return users
.filter(filter)
.slice(0, limit)
.map(({ name, age, ...rest }) => ({
displayName: `${name} (Age: ${age})`,
...rest
}));
}
const result = processUsers({
users: [
{ name: 'Alice', age: 25, role: 'admin' },
{ name: 'Bob', age: 30, role: 'user' }
],
filter: u => u.age > 20,
limit: 5
});
// Practical examples
function updateConfig(existingConfig, updates) {
return {
...existingConfig,
...updates,
updated: new Date()
};
}
function mergeArrays(...arrays) {
return [...new Set(arrays.flat())];
}
console.log(mergeArrays([1, 2], [2, 3], [3, 4]));
// [1, 2, 3, 4]
// Optional chaining (ES2020)
const userData = {
user: {
profile: {
name: 'Alice'
}
}
};
console.log(userData?.user?.profile?.name); // Alice
console.log(userData?.user?.settings?.theme); // undefined
// Nullish coalescing (ES2020)
const value = null ?? 'default'; // 'default'
const zero = 0 ?? 'default'; // 0 (different from ||)