incorrect();
correct();
function incorrect() {
console.log("**** Wrong way to edit a object prop in a copied array with the spread operator ****")
const list = [
{
"name": "Angel",
"age": 20,
},
{
"name": "Alex",
"age": 18,
}
];
const listCopy = [...list];
console.log("- Before editing the value of the second element");
console.log("list: ", list);
console.log("listCopy: ", listCopy);
listCopy[1].age = 99;
console.log("\n- After setting the age value to 99 of the second element");
console.log("listCopy: ", listCopy);
console.log("list: ", list);
}
function correct() {
console.log("\n\n**** Correct way to edit a object prop in a copied array with the spread operator ****")
const list = [
{
"name": "Angel",
"age": 20,
},
{
"name": "Alex",
"age": 18,
}
];
const listCopy = [...list];
console.log("- Before editing the value of the second element");
console.log("list: ", list);
console.log("listCopy: ", listCopy);
listCopy[1] = { ...list[1], "age": 99 };
console.log("\n- After setting the age value to 99 of the second element");
console.log("listCopy: ", listCopy);
console.log("list: ", list);
}
To embed this project on your website, copy the following code and paste it into your website's HTML: