Skip to content

Commit b9535d2

Browse files
committed
Ex14 - ref vs copying
1 parent a996e6f commit b9535d2

File tree

2 files changed

+90
-0
lines changed

2 files changed

+90
-0
lines changed
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
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+
<script src="script.js" charset="utf-8"></script>
9+
</body>
10+
</html>
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
'use strict';
2+
3+
// start with strings, numbers and booleans
4+
// type primitif => passage par copie
5+
6+
// Let's say we have an array
7+
const players = ['Wes', 'Sarah', 'Ryan', 'Poppy'];
8+
9+
// and we want to make a copy of it.
10+
11+
// objet => passage par reference
12+
13+
// You might think we can just do something like this:
14+
15+
// however what happens when we update that array?
16+
17+
// now here is the problem!
18+
19+
// oh no - we have edited the original array too!
20+
21+
// Why? It's because that is an array reference, not an array copy. They both point to the same array!
22+
23+
// So, how do we fix this? We take a copy instead!
24+
var copy = players.slice();
25+
var copy2 = [].concat(players);
26+
var copy3 = [...players];
27+
var copy4 = Array.from(players);
28+
29+
30+
// one day
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+
const captain = {
42+
name: 'igloo',
43+
age: 76
44+
}
45+
46+
47+
// and think we make a copy:
48+
49+
// how do we take a copy instead?
50+
const marin = Object.assign({}, captain, {age: 99, barbe: true});
51+
console.log(marin);
52+
53+
// We will hopefully soon see the object ...spread
54+
55+
// 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.
56+
57+
// => SHALLOW COPY!
58+
59+
60+
61+
62+
let obj1 = {
63+
name: 'obj1',
64+
age: {
65+
number: 60,
66+
unit: 'years'
67+
}
68+
};
69+
70+
const obj2 = Object.assign({}, obj1);
71+
72+
//Poor man's deep clone, not recommended. Probably not the best performance wise !
73+
const obj3 = JSON.parse(JSON.stringify(obj1));
74+
75+
obj1.age.unit = 'months';
76+
77+
78+
console.log(obj1);
79+
console.log(obj2);
80+
console.log(obj3);

0 commit comments

Comments
 (0)