Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit d3c9bc4

Browse files
committed
Complete references vs coppying wesbos#14
1 parent 3f34dcf commit d3c9bc4

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

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

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,33 @@
88

99
<script>
1010
// 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 name = 'Wes';
18+
let name2 = name;
19+
console.log(name, name);
20+
name = 'Wesley';
21+
console.log(name, name2)
1122

1223
// Let's say we have an array
1324
const players = ['Wes', 'Sarah', 'Ryan', 'Poppy'];
1425

1526
// and we want to make a copy of it.
27+
const team = players
28+
29+
console.log(players, team);
1630

1731
// You might think we can just do something like this:
32+
// team[3] = 'Lux';
1833

1934
// however what happens when we update that array?
35+
// team is just the reference to the original array.
36+
// So when you edit that original array it's aloways going to go back to the reference
37+
// If you update an array it will always reference back!
2038

2139
// now here is the problem!
2240

@@ -26,11 +44,22 @@
2644

2745
// So, how do we fix this? We take a copy instead!
2846

47+
const team2 = players.slice();
48+
49+
50+
// If you pass slice nothing it will take a copy of the original
51+
2952
// one way
3053

3154
// or create a new array and concat the old one in
55+
const team3 = [].concat(players);
3256

3357
// or use the new ES6 Spread
58+
const team4 = [...players];
59+
team4[3] = 'hee haw'
60+
console.log(team4);
61+
62+
const team5 = Array.from(players)
3463

3564
// now when we update it, the original one isn't changed
3665

@@ -43,12 +72,36 @@
4372
};
4473

4574
// and think we make a copy:
75+
const captain = person;
76+
// captain.number = 99;
4677

4778
// how do we take a copy instead?
79+
const capt2 = Object.assign({}, person, { number: 99, age: 12 });
80+
console.log(capt2);
81+
// Here we take a blank object and fold in all the properties from the other object
82+
// And fold in our own properties
4883

4984
// We will hopefully soon see the object ...spread
85+
// const cap3 = {...person};
5086

5187
// 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.
88+
const wes = {
89+
name: 'Wes',
90+
age: 100,
91+
social: {
92+
twitter: '@wesbos',
93+
facebook: 'wesbos.developer'
94+
}
95+
};
96+
97+
console.clear();
98+
console.log(wes);
99+
100+
const dev = Object.assign({}, wes);
101+
102+
const dev2 = JSON.parse(JSON.stringify(wes));
103+
// The poor mans deepclone
104+
52105

53106
</script>
54107

0 commit comments

Comments
 (0)