Visitar URL original
Implemented reference vs copying · wesbos/JavaScript30@e2708ad · GitHub
Skip to content

Commit e2708ad

Browse files
committed
Implemented reference vs copying
1 parent 5d4b0d5 commit e2708ad

1 file changed

Lines changed: 70 additions & 0 deletions

File tree

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
<title>JS Reference VS Copy</title>
6+
</head>
7+
<body>
8+
9+
<script>
10+
// start with strings, numbers and booleans
11+
// let age = 100;
12+
// let age2 = age;
13+
// console.log(age, age2);
14+
// age = 200;
15+
// console.log(age, age2);
16+
17+
// Let's say we have an array
18+
const players = ['Wes', 'Sarah', 'Ryan', 'Poppy'];
19+
20+
// and we want to make a copy of it.
21+
const team = players;
22+
23+
// You might think we can just do something like this:
24+
//team[3] = 'Lux';
25+
26+
// however what happens when we update that array?
27+
28+
// now here is the problem!
29+
30+
// oh no - we have edited the original array too!
31+
32+
// Why? It's because that is an array reference, not an array copy. They both point to the same array!
33+
34+
// So, how do we fix this? We take a copy instead!
35+
const team2 = players.slice();
36+
37+
// one day
38+
39+
// or create a new array and concat the old one in
40+
const team3 = [].concat(players);
41+
42+
// or use the new ES6 Spread
43+
const team4 = [...players];
44+
45+
const team5 = Array.from(players);
46+
47+
// now when we update it, the original one isn't changed
48+
49+
// The same thing goes for objects, let's say we have a person object
50+
51+
// with Objects
52+
const person = {
53+
name: 'Wes Bos',
54+
age: 80
55+
};
56+
57+
// and think we make a copy:
58+
59+
// how do we take a copy instead?
60+
const cap2 = Object.assign({}, person, {age: 99});
61+
62+
// We will hopefully soon see the object ...spread
63+
//const cap3 = {...person};
64+
65+
// 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.
66+
67+
</script>
68+
69+
</body>
70+
</html>

0 commit comments

Comments
 (0)