@@ -643,26 +643,29 @@ console.log(newName); // ['Ryan', 'McDermott'];
643
643
644
644
### Avoid Side Effects (part 2)
645
645
646
- In JavaScript, primitives are passed by value and objects/arrays are passed by
647
- reference. In the case of objects and arrays, if your function makes a change
648
- in a shopping cart array, for example, by adding an item to purchase,
649
- then any other function that uses that ` cart ` array will be affected by this
650
- addition. That may be great, however it can be bad too. Let's imagine a bad
651
- situation:
646
+ In JavaScript, some values are unchangeable (immutable) and some are changeable
647
+ (mutable). Objects and arrays are two kinds of mutable values so it's important
648
+ to handle them carefully when they're passed as parameters to a function. A
649
+ JavaScript function can change an object's properties or alter the contents of
650
+ an array which could easily cause bugs elsewhere.
651
+
652
+ Suppose there's a function that accepts an array parameter representing a
653
+ shopping cart. If the function makes a change in that shopping cart array
654
+ - by adding an item to purchase, for example - then any other function that
655
+ uses that same ` cart ` array will be affected by this addition. That may be
656
+ great, however it could also be bad. Let's imagine a bad situation:
652
657
653
658
The user clicks the "Purchase" button which calls a ` purchase ` function that
654
659
spawns a network request and sends the ` cart ` array to the server. Because
655
660
of a bad network connection, the ` purchase ` function has to keep retrying the
656
- request. Now, what if in the meantime the user accidentally clicks "Add to Cart"
661
+ request. Now, what if in the meantime the user accidentally clicks an "Add to Cart"
657
662
button on an item they don't actually want before the network request begins?
658
663
If that happens and the network request begins, then that purchase function
659
- will send the accidentally added item because it has a reference to a shopping
660
- cart array that the ` addItemToCart ` function modified by adding an unwanted
661
- item.
664
+ will send the accidentally added item because the ` cart ` array was modified.
662
665
663
- A great solution would be for the ` addItemToCart ` to always clone the ` cart ` ,
664
- edit it, and return the clone. This ensures that no other functions that are
665
- holding onto a reference of the shopping cart will be affected by any changes.
666
+ A great solution would be for the ` addItemToCart ` function to always clone the
667
+ ` cart ` , edit it, and return the clone. This would ensure that functions that are still
668
+ using the old shopping cart wouldn't be affected by the changes.
666
669
667
670
Two caveats to mention to this approach:
668
671
0 commit comments