// spread operators can be used for arrays or objects
// cloning to prevent mutation.
let numList = [1,2,3];
let numListClone = [...numList]; // [1, 2, 3]
// spread operator for destructuring.
let animal = {
name: 'dog',
color: 'brown',
age: 7
};
let { age, ...otherProperties } = animal;
// spread operator as rest operator
function sum(x, y, ...rest) {}
// spread operator for merging arrays or objects
let numLists = [...numList1, ...numList2];
let animalWithBreed = {
...animal,
breed: '',
}
let arr1 = ['A', 'B', 'C'];
let arr2 = ['X', 'Y', 'Z'];
let result = [...arr1, ...arr2];
console.log(result); // ['A', 'B', 'C', 'X', 'Y', 'Z']
// spread elements of the array instead of taking the array as a whole
syntax:
...iterable
where, iterable is source like array, object, string etc
const a=[1,2]
console.log(...a)
// prints 1 2
***spread operator makes a copy of source, not reference.
// ex. - if a & b are 2 arrays
a=[...b]
//changing a won't affect b & vice versa
*Also since it copies source, something like this is also possible:
const a=[5,1]
const b=[2]
const c=[...b,...a]
// c is [2,5,1]
*********************************************
For object just use {} instead of []
const a={ap:4}
const c={...a}
var num = [2, 4, 6, 8, 10];
console.log(...num)
//expected output: 2 4 6 8 10
console.log(88, ...num, 99)
// added extra new elements before and after the spread operator
//expected output: 88 2 4 6 8 10 99
var num = [2, 4, 6, 8, 10];
console.log(...num)
//expected output: 2 4 6 8 10
console.log(88, ...num, 99)
// added extra new elements before and after the spread operator
//expected output: 88 2 4 6 8 10 99
var num = [2, 4, 6, 8, 10];
console.log(...num)
//expected output: 2 4 6 8 10
console.log(88, ...num, 99)
// added extra new elements before and after the spread operator
//expected output: 88 2 4 6 8 10 99
var num = [2, 4, 6, 8, 10];
console.log(...num)
//expected output: 2 4 6 8 10
console.log(88, ...num, 99)
// added extra new elements before and after the spread operator
//expected output: 88 2 4 6 8 10 99
var num = [2, 4, 6, 8, 10];
console.log(...num)
//expected output: 2 4 6 8 10
console.log(88, ...num, 99)
// added extra new elements before and after the spread operator
//expected output: 88 2 4 6 8 10 99