Skip to content

Commit fd1d1ee

Browse files
author
Alexander Besse
committed
wesbos#14 Completed.
1 parent 156ee6d commit fd1d1ee

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

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

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,27 @@
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, name2);
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;
1628

29+
console.log(players, team);
1730
// You might think we can just do something like this:
31+
// team[3] = 'Lux';
1832

1933
// however what happens when we update that array?
2034

@@ -25,12 +39,19 @@
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();
2843

2944
// one way
3045

3146
// or create a new array and concat the old one in
47+
const team3 = [].concat(players);
3248

3349
// or use the new ES6 Spread
50+
const team4 = [...players];
51+
team4[3] = 'heeee hawww';
52+
console.log(team4);
53+
54+
const team5 = Array.from(players);
3455

3556
// now when we update it, the original one isn't changed
3657

@@ -43,13 +64,35 @@
4364
};
4465

4566
// and think we make a copy:
67+
// const captain = person;
68+
// captain.number = 99;
4669

4770
// how do we take a copy instead?
71+
const cap2 = Object.assign({}, person, { number: 99, age: 12 });
72+
console.log(cap2);
4873

4974
// We will hopefully soon see the object ...spread
75+
// const cap3 = {...person};
5076

5177
// 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.
5278

79+
const wes = {
80+
name: 'Wes',
81+
age: 100,
82+
social: {
83+
twitter: '@wesbos',
84+
facebook: 'wesbos.developer'
85+
}
86+
};
87+
88+
console.clear();
89+
console.log(wes);
90+
91+
const dev = Object.assign({}, wes);
92+
93+
const dev2 = JSON.parse(JSON.stringify(wes));
94+
95+
5396
</script>
5497

5598
</body>

0 commit comments

Comments
 (0)