Skip to content

Commit 5e581f9

Browse files
Merge pull request ryanmcdermott#123 from kbariotis/patch-1
Add Side Effects pt.2
2 parents 7dabe47 + fae5111 commit 5e581f9

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

README.md

+33-1
Original file line numberDiff line numberDiff line change
@@ -514,7 +514,7 @@ function createTempFile(name) {
514514
```
515515
**[⬆ back to top](#table-of-contents)**
516516

517-
### Avoid Side Effects
517+
### Avoid Side Effects (part 1)
518518
A function produces a side effect if it does anything other than take a value in
519519
and return another value or values. A side effect could be writing to a file,
520520
modifying some global variable, or accidentally wiring all your money to a
@@ -559,6 +559,38 @@ console.log(newName); // ['Ryan', 'McDermott'];
559559
```
560560
**[⬆ back to top](#table-of-contents)**
561561

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+
562594
### Don't write to global functions
563595
Polluting globals is a bad practice in JavaScript because you could clash with another
564596
library and the user of your API would be none-the-wiser until they get an

0 commit comments

Comments
 (0)