|
| 1 | +<!DOCTYPE html> |
| 2 | +<htmllang="en"> |
| 3 | +<head> |
| 4 | +<metacharset="UTF-8"> |
| 5 | +<title>JS Reference VS Copy</title> |
| 6 | +</head> |
| 7 | +<body> |
| 8 | + |
| 9 | +<script> |
| 10 | +// start with strings, numbers and booleans |
| 11 | + |
| 12 | +// Let's say we have an array |
| 13 | +constplayers=['Wes','Sarah','Ryan','Poppy']; |
| 14 | + |
| 15 | +// and we want to make a copy of it. |
| 16 | +constteam=players; |
| 17 | + |
| 18 | +// You might think we can just do something like this: |
| 19 | +team[3]='Lux'; |
| 20 | + |
| 21 | +// however what happens when we update that array? |
| 22 | + |
| 23 | +// now here is the problem! |
| 24 | + |
| 25 | +// oh no - we have edited the original array too! |
| 26 | + |
| 27 | +// Why? It's because that is an array reference, not an array copy. They both point to the same array! |
| 28 | + |
| 29 | +// So, how do we fix this? We take a copy instead! |
| 30 | +constteam2=players.slice(); |
| 31 | + |
| 32 | +// one day |
| 33 | + |
| 34 | +// or create a new array and concat the old one in |
| 35 | +constteam3=[].concat(players); |
| 36 | + |
| 37 | +// or use the new ES6 Spread |
| 38 | +constteam4=[...players]; |
| 39 | + |
| 40 | +// now when we update it, the original one isn't changed |
| 41 | + |
| 42 | +// The same thing goes for objects, let's say we have a person object |
| 43 | + |
| 44 | +// with Objects |
| 45 | +constperson={ |
| 46 | +name: 'Wes Bos', |
| 47 | +age: 80 |
| 48 | +}; |
| 49 | + |
| 50 | +// and think we make a copy: |
| 51 | +constcaptain=person; |
| 52 | + |
| 53 | +// how do we take a copy instead? |
| 54 | +constcap2=Object.assign({},person,{number: 99,age: 12}); |
| 55 | + |
| 56 | +// We will hopefully soon see the object ...spread |
| 57 | +// const cap3 ={...person}; |
| 58 | + |
| 59 | +// 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. |
| 60 | +constwes={ |
| 61 | +name: 'Wes', |
| 62 | +age: 100, |
| 63 | +social: { |
| 64 | +twitter: '@wesbos', |
| 65 | +facebook: 'wesbos.developer' |
| 66 | +} |
| 67 | +}; |
| 68 | + |
| 69 | +constdev=Object.assign([],wes); |
| 70 | +</script> |
| 71 | + |
| 72 | +</body> |
| 73 | +</html> |
0 commit comments