Skip to content

Add examples for pure functions and destructuring defaults #704

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1033,6 +1033,40 @@ function newRequestModule(url) {
const req = newRequestModule;
inventoryTracker("apples", req, "www.inventory-awesome.io");
```
**[⬆ back to top](#table-of-contents)**

#### Pure Functions vs. Side Effects

- A **pure function** only uses its input values and doesn’t change anything outside itself.
- A **side effect** is any change to external state (mutating arguments, globals, etc.).

**Why?**
- Predictable: gives the same result every time for the same inputs.
- Easy to test: no hidden state to reset or mock.
- Safe to reuse and refactor without unintended consequences.

**Bad:**
```js
let total = 0;

function addToCart(cart, item) {
cart.push(item); // ← side effect: changing external cart
total += item.price; // ← side effect: changes external `total`
return cart.length;
}
```
**Good:**
```js
function addToCart(cart, item) {
// returns a new cart array without touching the original
return [...cart, item];
}

function calculateTotal(cart) {
// pure computation: only reads input, never writes out
return cart.reduce((sum, item) => sum + item.price, 0);
}
```

**[⬆ back to top](#table-of-contents)**

Expand Down Expand Up @@ -1136,6 +1170,35 @@ console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe
delete employee.name;
console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe
```
**[⬆ back to top](#table-of-contents)**

#### Destructuring Defaults & Nested Destructuring

It lets you set default values for object properties right in the function signature and prevents errors if a nested object isn’t provided.

**Why?**
- Eliminates repetitive `||` defaulting.
- You can see what values the function uses and their fallback values right in its definition.
- Prevents runtime errors when nested objects are omitted.

**Bad:**
```js
function connectToDatabase(opts) {
const host = opts.host || 'localhost';
const port = opts.port || 80;
const db = opts.db || { name: 'test' };
}
```

**Good:**
```js
function connectToDatabase({
host = 'localhost',
port = 80,
db: { name = 'test' } = {}
} = {}) {
}
```

**[⬆ back to top](#table-of-contents)**

Expand Down