Spread Operator use cases Flashcards

1
Q

Combining arrays: The spread operator can be used to combine two or more arrays into a single array.

A

let array1 = [1, 2, 3];
let array2 = [4, 5, 6];
let combinedArray = […array1, …array2];
console.log(combinedArray);
// Output: [1, 2, 3, 4, 5, 6]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Copying arrays: The spread operator can also be used to make a shallow copy of an array.

A

let originalArray = [1, 2, 3];
let copyArray = […originalArray];
console.log(copyArray);
// Output: [1, 2, 3]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Passing function arguments: The spread operator can be used to pass elements of an array as separate arguments to a function.

A

function sum(a, b, c) {
return a + b + c;
}
let numbers = [1, 2, 3];
console.log(sum(…numbers));
// Output: 6

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Object destructuring: The spread operator can be used in object destructuring to merge objects into a single object.

A

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 }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

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.

A

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 }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

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.

A

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 }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly