Skip to content

Commit 7f55a7b

Browse files
committed
Completed lesson 14
Going deep inside clones.
1 parent 2276704 commit 7f55a7b

File tree

1 file changed

+30
-2
lines changed

1 file changed

+30
-2
lines changed

14 - JavaScript References VS Copying/index-START.html

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,29 @@
88

99
<script>
1010
// start with strings, numbers and booleans
11+
let age = 100;
12+
let otherAge = age;
13+
console.log(age, otherAge); // 100 100
14+
age = 200;
15+
console.log(age, otherAge); // 200 100
16+
17+
let name = "Robert";
18+
let otherName = name;
19+
console.log(name, otherName); // Robert Robert
20+
name = "Billy";
21+
console.log(name, otherName); // Billy Robert
1122

1223
// Let's say we have an array
13-
const players = ['Wes', 'Sarah', 'Ryan', 'Poppy'];
24+
const players = ["Robert", "Laura", "Mitzi", "Lucy"];
1425

1526
// and we want to make a copy of it.
27+
const team = players;
1628

1729
// You might think we can just do something like this:
30+
players[3] = "Tommy";
1831

1932
// however what happens when we update that array?
33+
console.log(team); // ["Robert", "Laura", "Mitzi", "Tommy"]
2034

2135
// now here is the problem!
2236

@@ -25,27 +39,41 @@
2539
// Why? It's because that is an array reference, not an array copy. They both point to the same array!
2640

2741
// So, how do we fix this? We take a copy instead!
42+
const team2 = players.slice();
43+
const team3 = [].concat(players);
2844

2945
// one day
3046

3147
// or create a new array and concat the old one in
3248

3349
// or use the new ES6 Spread
50+
const team4 = [...players];
51+
const team5 = Array.from(players);
3452

3553
// now when we update it, the original one isn't changed
3654

3755
// The same thing goes for objects, let's say we have a person object
3856

3957
// with Objects
58+
const person = {
59+
name: "Robert Mion",
60+
age: 29
61+
};
4062

4163
// and think we make a copy:
64+
const captain = person
65+
captain.number = 99;
66+
console.log(person); // { name: "Robert Mion", age: 29, number: 99 }
4267

4368
// how do we take a copy instead?
69+
const cap2 = Object.assign({}, person, { number: 29, age: 12 });
70+
console.log(person) // { name: "Robert Mion", age: 29 }
4471

4572
// We will hopefully soon see the object ...spread
73+
// const cap3 = {...person} // Woah!
4674

4775
// Things to note - this is only 1 level deep - both for Arrays and Objects. lodash has a cloneDeep method, but you should think twice before using it.
48-
76+
const cap4 = JSON.parse(JSON.stringify(person)); // Poor man's deep clone
4977
</script>
5078

5179
</body>

0 commit comments

Comments
 (0)