ES6+ Spread Operator
Spread operator '...' will take data from an array and send it as comma seperated values
Example1:
const nums = [1, 2, 3, 4];
console.log(...nums);
- Will return the values in the array
- The code sent to the console.log is 1,2,3,4
Example2:
//declaration of the function
function calc(x,y,z) {
return x * y + z;
}
// declaration of the array
const nums = [3, 5, 8];
//assignment of the values of the array as the operators in the function
console.log(cal(...nums);)
- Will return the result of calculation
in JavaScript, assigning an object to another object creates a twin.
a change in the new object will affect the original object.
When declaring an object
let person1 = {
name = 'Guy',
age = 46
}
and assigning it to a now object
let person2 = person1;
when we modify a child in the new object
person2.name = 'Ofek';
the original object will be affected too
console.log(person1.name) //will return 'Ofek'
Instead, Spread Operator can be used to create a duplicate of the object, that will have its own life
let person2 = {...person1}; //assigning old boject to a new object
person2.name = 'Ofek' //modifying a child object in the new object
console.log(person1.name); //will return 'Guy'
//Does not affect the original object
Although this will make a duplicate of the object, a child object will still be a linked clone
let grandpa = {
name: 'Yosef',
age: 80,
father: {
name: 'Meni',
age: 50
kid: {
name: 'Snir',
age: 17
}
}
};
And changing a value of a child object in one object
let grandpa2 = {...grandpa1
};
grandpa2.name = 'Avraham';
grandpa2.father.name = 'Itzhak';
grandpa2.father.kid.name = 'Rave';
will affect the other
grandpa1:
name: "Yosef"
age: 80,
father:
name: "Itzhak",
age: 50
kid:
name: "Rave"
age: 17
The best way to create a full duplicate of object with child objects is with
JSON.stringify
grandpa2 = JSON.parse(JSON.stringify(grandpa1));
This way each duplicate will have its own life , including its decendents
back to main page