You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
<p><em>Psst: have a look at the JavaScript Console</em> 💁</p>
9
+
10
+
<script>
11
+
// start with strings, numbers and booleans
12
+
13
+
// Let's say we have an array
14
+
constplayers=['Wes','Sarah','Ryan','Poppy'];
15
+
16
+
// and we want to make a copy of it.
17
+
18
+
// You might think we can just do something like this:
19
+
20
+
// however what happens when we update that array?
21
+
22
+
// now here is the problem!
23
+
24
+
// oh no - we have edited the original array too!
25
+
26
+
// Why? It's because that is an array reference, not an array copy. They both point to the same array!
27
+
28
+
// So, how do we fix this? We take a copy instead!
29
+
30
+
// one way
31
+
32
+
// or create a new array and concat the old one in
33
+
34
+
// or use the new ES6 Spread
35
+
36
+
// now when we update it, the original one isn't changed
37
+
38
+
// The same thing goes for objects, let's say we have a person object
39
+
40
+
// with Objects
41
+
constperson={
42
+
name: 'Wes Bos',
43
+
age: 80
44
+
};
45
+
46
+
// and think we make a copy:
47
+
48
+
// how do we take a copy instead?
49
+
50
+
// We will hopefully soon see the object ...spread
51
+
52
+
// 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.
<p><em>Psst: have a look at the JavaScript Console</em> 💁</p>
9
+
10
+
<script>
11
+
// start with strings, numbers and booleans
12
+
13
+
// Let's say we have an array
14
+
constplayers=['Wes','Sarah','Ryan','Poppy'];
15
+
16
+
// and we want to make a copy of it.
17
+
18
+
// You might think we can just do something like this:
19
+
20
+
// however what happens when we update that array?
21
+
22
+
// now here is the problem!
23
+
24
+
// oh no - we have edited the original array too!
25
+
26
+
// Why? It's because that is an array reference, not an array copy. They both point to the same array!
27
+
28
+
// So, how do we fix this? We take a copy instead!
29
+
30
+
// one way
31
+
32
+
// or create a new array and concat the old one in
33
+
34
+
// or use the new ES6 Spread
35
+
36
+
// now when we update it, the original one isn't changed
37
+
38
+
// The same thing goes for objects, let's say we have a person object
39
+
40
+
// with Objects
41
+
constperson={
42
+
name: 'Wes Bos',
43
+
age: 80
44
+
};
45
+
46
+
// and think we make a copy:
47
+
48
+
// how do we take a copy instead?
49
+
50
+
// We will hopefully soon see the object ...spread
51
+
52
+
// 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.
0 commit comments