|
| 1 | +<!DOCTYPE html> |
| 2 | +<html lang="en"> |
| 3 | +<head> |
| 4 | + <meta charset="UTF-8"> |
| 5 | + <title>JS Reference VS Copy</title> |
| 6 | +</head> |
| 7 | +<body> |
| 8 | + |
| 9 | + <script> |
| 10 | + // start with strings, numbers and booleans |
| 11 | + let age = 100; |
| 12 | + let age2 = age; |
| 13 | + console.log('age', age, 'age2', age2); |
| 14 | + |
| 15 | + age = 200; |
| 16 | + console.log('age', age, 'age2', age2); |
| 17 | + |
| 18 | + let name = 'Wes'; |
| 19 | + let name2 = name; |
| 20 | + console.log('name', name, 'name2', name2); |
| 21 | + |
| 22 | + name = 'wesley'; |
| 23 | + console.log('name', name, 'name2', name2); |
| 24 | + |
| 25 | + // Let's say we have an array |
| 26 | + const players = ['Wes', 'Sarah', 'Ryan', 'Poppy']; |
| 27 | + |
| 28 | + // and we want to make a copy of it. |
| 29 | + |
| 30 | + // You might think we can just do something like this: |
| 31 | + |
| 32 | + // however what happens when we update that array? |
| 33 | + |
| 34 | + // now here is the problem! |
| 35 | + |
| 36 | + // oh no - we have edited the original array too! |
| 37 | + |
| 38 | + // Why? It's because that is an array reference, not an array copy. They both point to the same array! |
| 39 | + |
| 40 | + // So, how do we fix this? We take a copy instead! |
| 41 | + |
| 42 | + // one way |
| 43 | + |
| 44 | + // or create a new array and concat the old one in |
| 45 | + |
| 46 | + // or use the new ES6 Spread |
| 47 | + |
| 48 | + // now when we update it, the original one isn't changed |
| 49 | + |
| 50 | + // The same thing goes for objects, let's say we have a person object |
| 51 | + |
| 52 | + // with Objects |
| 53 | + |
| 54 | + // and think we make a copy: |
| 55 | + |
| 56 | + // how do we take a copy instead? |
| 57 | + |
| 58 | + // We will hopefully soon see the object ...spread |
| 59 | + |
| 60 | + // 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. |
| 61 | + |
| 62 | + </script> |
| 63 | + |
| 64 | +</body> |
| 65 | +</html> |
0 commit comments