xxxxxxxxxx
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
xxxxxxxxxx
// 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: '',
}
xxxxxxxxxx
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
xxxxxxxxxx
const parts = ['shoulders', 'knees'];
const lyrics = ['head', parts, 'and', 'toes'];
// ["head", "shoulders", "knees", "and", "toes"]
xxxxxxxxxx
function sum(x, y, z) {
return x + y + z;
}
const numbers = [1, 2, 3];
console.log(sum(numbers));
// expected output: 6
console.log(sum.apply(null, numbers));
// expected output: 6
xxxxxxxxxx
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
xxxxxxxxxx
obj = {first_name : "Marty",
lovers: ["Jennifer Parker","Baines McFly"]
};
let objClone = { obj }; // pass all key:value pairs from an object
console.log(objClone)
// { first_name: "Marty", lovers: ["Jennifer Parker", "Baines McFly"] }
xxxxxxxxxx
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}
xxxxxxxxxx
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
xxxxxxxxxx
var num = [2, 4, 6, 8, 10];
console.log(num)
//expected output: 2 4 6 8 10
console.log(88, num, 99)
//expected output: 88 2 4 6 8 10 99