@@ -514,7 +514,7 @@ function createTempFile(name) {
|
514 | 514 | ```
|
515 | 515 | **[⬆ back to top](#table-of-contents)**
|
516 | 516 |
|
517 |
| -### Avoid Side Effects |
| 517 | +### Avoid Side Effects (part 1) |
518 | 518 | A function produces a side effect if it does anything other than take a value in
|
519 | 519 | and return another value or values. A side effect could be writing to a file,
|
520 | 520 | modifying some global variable, or accidentally wiring all your money to a
|
@@ -559,6 +559,38 @@ console.log(newName); // ['Ryan', 'McDermott'];
|
559 | 559 | ```
|
560 | 560 | **[⬆ back to top](#table-of-contents)**
|
561 | 561 |
|
| 562 | +### Avoid Side Effects (part 2) |
| 563 | +Side effects could also occur from inside a function. In JavaScript, primitives are |
| 564 | +passed by value and objects are passed by reference. In the later case, we should be |
| 565 | +careful not to change any of these argument's properties. |
| 566 | + |
| 567 | +A possible solution would be to always clone the variable, edit it and return the |
| 568 | +clone. There would be cases where you actually want to modify the input object |
| 569 | +and this should not be taken as a silver bullet. Furthermore, cloning big objects can |
| 570 | +be very expensive in terms of performance. |
| 571 | + |
| 572 | +**Bad:** |
| 573 | +```javascript |
| 574 | +const addItemToCart = (cart, item) => { |
| 575 | +cart.push({ item, date: Date.now() }); |
| 576 | + |
| 577 | +return cart; |
| 578 | +}; |
| 579 | +``` |
| 580 | + |
| 581 | +**Good:** |
| 582 | +```javascript |
| 583 | +const addItemToCart = (cart, item) => { |
| 584 | +const c = Object.assign({}, cart); |
| 585 | + |
| 586 | +c.push({ item, date: Date.now() }); |
| 587 | + |
| 588 | +return c; |
| 589 | +}; |
| 590 | +``` |
| 591 | + |
| 592 | +**[⬆ back to top](#table-of-contents)** |
| 593 | + |
562 | 594 | ### Don't write to global functions
|
563 | 595 | Polluting globals is a bad practice in JavaScript because you could clash with another
|
564 | 596 | library and the user of your API would be none-the-wiser until they get an
|
|
0 commit comments