JavaScript · Syntax · Intermediate
Destructuring and spread
Extract values from arrays and objects in one line. Covers destructuring assignment, spread operator, and rest parameters.
Quick topic start and explanations before exercises (exercises below):
Rest parameters, spread in arrays and objects, shallow copy gotcha
#Practical patterns: swap, minMax, omit, pick, config merging
#Exercises:
Array destructuring
#Write a function that takes an array of at least three elements and returns an object with properties first, second, and rest (an array of the remaining elements). Use array destructuring.
function splitArray(arr) {
}
console.log(splitArray([1, 2, 3, 4, 5]));
Solution
function splitArray(arr) {
const [first, second, ...rest] = arr;
return { first, second, rest };
}
console.log(splitArray([1, 2, 3, 4, 5]));
Object destructuring
#Write a function that takes a user object (with name, age, and email properties) and returns a greeting string using only the name and age. Use object destructuring in the function parameters.
function greetUser({ name, age }) {
}
console.log(greetUser({ name: "Alice", age: 30, email: "[email protected]" }));
Solution
function greetUser({ name, age }) {
return `Hello, ${name}! You are ${age} years old.`;
}
console.log(greetUser({ name: "Alice", age: 30, email: "[email protected]" }));
Swap variables
#Write a function that takes two values and returns them in swapped order. Use array destructuring to perform the swap in one line.
function swap(a, b) {
}
console.log(swap(1, 2));
console.log(swap("hello", "world"));
Solution
function swap(a, b) {
[a, b] = [b, a];
return [a, b];
}
console.log(swap(1, 2));
console.log(swap("hello", "world"));
Merge objects
#Write a function that takes two objects and returns a new object that contains all properties from both. If a property exists in both, the second object's value should win. Use the spread operator.
function mergeObjects(obj1, obj2) {
}
console.log(mergeObjects({ a: 1, b: 2 }, { b: 3, c: 4 }));
Solution
function mergeObjects(obj1, obj2) {
return { ...obj1, ...obj2 };
}
console.log(mergeObjects({ a: 1, b: 2 }, { b: 3, c: 4 }));
Clone and update
#Write a function that takes a user object and a new name, and returns a new object that is a copy of the user with the name updated. Do not modify the original. Use the spread operator.
function updateName(user, newName) {
}
const user = { name: "Alice", age: 30, role: "admin" };
const updated = updateName(user, "Bob");
console.log(user);
console.log(updated);
Solution
function updateName(user, newName) {
return { ...user, name: newName };
}
const user = { name: "Alice", age: 30, role: "admin" };
const updated = updateName(user, "Bob");
console.log(user);
console.log(updated);
Default values in destructuring
#Write a function that takes a config object and returns a settings object with defaults applied. Use destructuring with default values: theme defaults to 'light', fontSize to 16, and language to 'en'.
function applyDefaults(config) {
}
console.log(applyDefaults({ theme: 'dark' }));
console.log(applyDefaults({ fontSize: 20, language: 'uk' }));
Solution
function applyDefaults({ theme = 'light', fontSize = 16, language = 'en' } = {}) {
return { theme, fontSize, language };
}
console.log(applyDefaults({ theme: 'dark' }));
console.log(applyDefaults({ fontSize: 20, language: 'uk' }));
Spread into function call
#Write a function that takes an array of numbers and returns the largest one, using Math.max() with the spread operator (Math.max does not accept an array directly).
function maxValue(numbers) {
}
console.log(maxValue([3, 1, 4, 1, 5, 9, 2, 6]));
Solution
function maxValue(numbers) {
return Math.max(...numbers);
}
console.log(maxValue([3, 1, 4, 1, 5, 9, 2, 6]));
Rest parameters
#Write a function sum(...numbers) that accepts any number of arguments and returns their sum.
function sum(...numbers) {
}
console.log(sum(1, 2, 3));
console.log(sum(10, 20, 30, 40, 50));
Solution
function sum(...numbers) {
return numbers.reduce((acc, n) => acc + n, 0);
}
console.log(sum(1, 2, 3));
console.log(sum(10, 20, 30, 40, 50));
Rename on destructure
#Write a function that takes a product object (with 'name' and 'price' properties) and returns a new object with the properties renamed to 'title' and 'cost'. Use destructuring with renaming.
function renameProduct(product) {
}
console.log(renameProduct({ name: "Widget", price: 9.99 }));
Solution
function renameProduct(product) {
const { name: title, price: cost } = product;
return { title, cost };
}
console.log(renameProduct({ name: "Widget", price: 9.99 }));
Combine arrays without duplicates
#Write a function that takes two arrays and returns a new array containing all unique values from both, in order (no duplicates). Use spread and Set.
function uniqueMerge(arr1, arr2) {
}
console.log(uniqueMerge([1, 2, 3, 4], [3, 4, 5, 6]));
Solution
function uniqueMerge(arr1, arr2) {
return [...new Set([...arr1, ...arr2])];
}
console.log(uniqueMerge([1, 2, 3, 4], [3, 4, 5, 6]));