Skip to content

Commit f5db7f5

Browse files
author
Kyle Bradshaw
committed
14 js references v copying
1 parent 9c1cbf7 commit f5db7f5

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

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

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,17 @@
88

99
<script>
1010
// start with strings, numbers and booleans
11+
let age = 100;
1112

1213
// Let's say we have an array
1314
const players = ['Wes', 'Sarah', 'Ryan', 'Poppy'];
1415

1516
// and we want to make a copy of it.
17+
const team = players;
18+
console.log(players, team);
1619

1720
// You might think we can just do something like this:
21+
team[3] = 'Lux'; //updating an array will always reference back
1822

1923
// however what happens when we update that array?
2024

@@ -25,26 +29,60 @@
2529
// Why? It's because that is an array reference, not an array copy. They both point to the same array!
2630

2731
// So, how do we fix this? We take a copy instead!
32+
const team2 = players.slice(); //makes a copy(entire array)
2833

2934
// one day
3035

36+
3137
// or create a new array and concat the old one in
38+
const team3 = [].concat(players);
3239

3340
// or use the new ES6 Spread
41+
const team4 = [...players];
42+
team4[3] = 'wacko';
43+
console.log(team4);
3444

3545
// now when we update it, the original one isn't changed
46+
const team5 = Array.from(players);
3647

3748
// The same thing goes for objects, let's say we have a person object
3849

3950
// with Objects
51+
const dog = {
52+
name: 'Porter',
53+
age: 5
54+
};
4055

4156
// and think we make a copy:
57+
const captain = dog;
58+
captain.age = 99;
4259

4360
// how do we take a copy instead?
61+
const cap2 = Object.assign({}, dog, { age: 100});
62+
console.log(cap2);
4463

4564
// We will hopefully soon see the object ...spread
4665

4766
// 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.
67+
const porter = {
68+
name: 'Porter',
69+
social: {
70+
twitter: '@porter',
71+
facebook: 'porter.dog'
72+
}
73+
};
74+
console.clear();
75+
console.log(porter);
76+
77+
const special = Object.assign({}, porter);
78+
console.log(special,'super');
79+
80+
//to make a deep copy
81+
82+
const dev = Object.assign({}, porter);
83+
const dev2 = JSON.parse(JSON.stringify(porter));
84+
85+
console.log(dev,dev2);
4886

4987
</script>
5088

0 commit comments

Comments
 (0)