Created by
let x = 1;
let y = x; // y stores the copy of "x" value
// we change the value in "x", but that did not reflect "y"
x = 9;
console.log(`x = ${x}`);
console.log(`y = ${y}`);
let arr1 = [1,2,3];
let arr2 = arr1; // "arr2" stores a reference to the "arr1"
// we change a value in "arr1", and that WILL reflect the "arr2"
arr1[0] = 9;
console.log(`arr1: ${arr1}`);
console.log(`arr2: ${arr2}`);
// arr1: 9,2,3
// arr2: 9,2,3
let user1 = {
name: "Maria",
age: 33
}
let user2 = user1; // "user2" stores a reference to the "user1" object
// we change a value in "user1", and that WILL reflect the "user2" object:
user1.name = "Pesho";
console.log(`user1: ${user1.name}`);
console.log(`user2: ${user2.name}`);
// user1: Pesho
// user2: Pesho
spread
operator - the easiest way
let arr1 = [1,2,3];
let arr2 = [...arr1];
// we change a value in "arr1", and that WILL NOT reflect the "arr2" copy:
arr1[0] = 9;
console.log(`arr1: ${arr1}`);
console.log(`arr2: ${arr2}`);
arr.slice()
method
let arr1 = [1,2,3];
let arr2 = arr1.slice();
// we change a value in "arr1", and that WILL NOT reflect the "arr2" copy:
arr1[0] = 9;
console.log(`arr1: ${arr1}`);
console.log(`arr2: ${arr2}`);
spread
operator - the easiest way
let user1 = {
name: "Maria",
age: 33
};
let user2 = {...user1}; // make shallow copy
// we change a value in "user1", and that WILL NOT reflect the "user2" object:
user1.name = "Pesho";
console.log(`user1: ${user1.name}`);
console.log(`user2: ${user2.name}`);
Object.assign()
method
let user1 = {
name: "Maria",
age: 33
}
let user2 = Object.assign({}, user1); // make shallow copy
// we change a value in "user1", and that WILL NOT reflect the "user2" object:
user1.name = "Pesho";
console.log(`user1: ${user1.name}`);
console.log(`user2: ${user2.name}`);
Reference: Object.assign() @MDN
let user1 = {
name: "Maria",
age: 33,
colors:["red","green"]
}
let user2 = JSON.parse(JSON.stringify(user1));
user1.colors[0] = "black";
console.log(user2.colors);
Object Copying @wikipedia.org
true
only if two variables point to the same object in memory.
let arr1 = [1,2,3];
let arrRef = arr1;
let arrCopy = [...arr1];
console.log(`arr1 === arrRef: ${arr1 === arrRef}`);
console.log(`arr1 === arrCopy: ${arr1 === arrCopy}`);
// arr1 === arrRef: true
// arr1 === arrCopy: false
These slides are based on
customised version of
framework