Skip to content

Commit 47aa0eb

Browse files
committed
Lesson 14
1 parent aedb1b4 commit 47aa0eb

1 file changed

Lines changed: 41 additions & 0 deletions

File tree

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

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,27 @@
99

1010
<script>
1111
// start with strings, numbers and booleans
12+
// let age = 100;
13+
// let age2 = age;
14+
// console.log(age, age2);
15+
// age = 200;
16+
// console.log(age, age2);
17+
18+
// let name = 'Wes';
19+
// let name2 = name;
20+
// console.log(name, name2);
21+
// name = 'wesley';
22+
// console.log(name, name2);
1223

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

1627
// and we want to make a copy of it.
28+
const team = players;
1729

30+
console.log(players, team);
1831
// You might think we can just do something like this:
32+
// team[3] = 'Lux';
1933

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

@@ -26,12 +40,19 @@
2640
// Why? It's because that is an array reference, not an array copy. They both point to the same array!
2741

2842
// So, how do we fix this? We take a copy instead!
43+
const team2 = players.slice();
2944

3045
// one way
3146

3247
// or create a new array and concat the old one in
48+
const team3 = [].concat(players);
3349

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

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

@@ -44,13 +65,33 @@
4465
};
4566

4667
// and think we make a copy:
68+
// const captain = person;
69+
// captain.number = 99;
4770

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

5075
// We will hopefully soon see the object ...spread
76+
const cap3 = {...person};
5177

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

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

5697
</body>

0 commit comments

Comments
 (0)