Spread Operator use cases Flashcards
Combining arrays: The spread operator can be used to combine two or more arrays into a single array.
let array1 = [1, 2, 3];
let array2 = [4, 5, 6];
let combinedArray = […array1, …array2];
console.log(combinedArray);
// Output: [1, 2, 3, 4, 5, 6]
Copying arrays: The spread operator can also be used to make a shallow copy of an array.
let originalArray = [1, 2, 3];
let copyArray = […originalArray];
console.log(copyArray);
// Output: [1, 2, 3]
Passing function arguments: The spread operator can be used to pass elements of an array as separate arguments to a function.
function sum(a, b, c) {
return a + b + c;
}
let numbers = [1, 2, 3];
console.log(sum(…numbers));
// Output: 6
Object destructuring: The spread operator can be used in object destructuring to merge objects into a single object.
let obj1 = { a: 1, b: 2 };
let obj2 = { c: 3, d: 4 };
let mergedObj = { …obj1, …obj2 };
console.log(mergedObj);
// Output: { a: 1, b: 2, c: 3, d: 4 }
Merging objects with overlapping keys: In the case of overlapping keys, the value from the last merged object will overwrite the values from previous objects.
let obj1 = { a: 1, b: 2 };
let obj2 = { b: 3, c: 4 };
let mergedObj = { …obj1, …obj2 };
console.log(mergedObj);
// Output: { a: 1, b: 3, c: 4 }
Merging objects with nested objects: The spread operator only performs a shallow merge of objects, so if an object has a nested object, the spread operator will only merge the top-level keys, not the nested keys.
let obj1 = { a: 1, b: { c: 2 } };
let obj2 = { b: { d: 3 }, e: 4 };
let mergedObj = { …obj1, …obj2 };
console.log(mergedObj);
// Output: { a: 1, b: { d: 3 }, e: 4 }