~/
hackweb.dev
JavaScript Array Methods
Quiz
⌘K
...
~/
/tutorials
/js/js-array-methods/edit
~ Contribute
Suggest a correction or improvement. The author reviews it before it goes live.
Loading...
Comment
0 / 300
Typo
Grammar
Broken link
Clarify
Code
en/tutorials/js/12js-array-methods
Write
Preview
Diff
# JavaScript Array Methods Array methods transform and query arrays without manual loops. ## Map Creates a new array by transforming each element: ```javascript let numbers = [1, 2, 3, 4, 5]; let doubled = numbers.map((n) => n * 2); // [2, 4, 6, 8, 10] ``` ## Filter Creates a new array with elements that pass a test: ```javascript let numbers = [1, 2, 3, 4, 5]; let evens = numbers.filter((n) => n % 2 === 0); // [2, 4] ``` ## Reduce Reduces an array to a single value: ```javascript let numbers = [1, 2, 3, 4, 5]; let sum = numbers.reduce((acc, curr) => acc + curr, 0); // 15 ``` **Remember:** Always provide an initial value to `reduce` to avoid errors with empty arrays. ## forEach Executes a function for each element (no return value): ```javascript let numbers = [1, 2, 3]; numbers.forEach((n, i) => console.log(`Index ${i}: ${n}`)); ``` **Tip:** Use `forEach` for side effects, `map` for transformations. ## Find and FindIndex ```javascript let users = [ { id: 1, name: "Alice" }, { id: 2, name: "Bob" } ]; let user = users.find((u) => u.id === 2); // { id: 2, name: "Bob" } let index = users.findIndex((u) => u.id === 2); // 1 ``` ## some and every ```javascript let numbers = [1, 2, 3, 4, 5]; numbers.some((n) => n % 2 === 0); // true (at least one) numbers.every((n) => n > 0); // true (all) ``` ## Complete Example: Data Pipeline ```javascript let products = [ { name: "Laptop", price: 999, inStock: true }, { name: "Phone", price: 699, inStock: false }, { name: "Tablet", price: 499, inStock: true } ]; let names = products.filter((p) => p.inStock).map((p) => p.name); let total = products.filter((p) => p.inStock).reduce((s, p) => s + p.price, 0); console.log(names); // ["Laptop", "Tablet"] console.log(total); // 1498 ``` ## Best Practices 1. **Use `map` for transformations** — not for side effects 2. **Use `filter` for selection** — not manual `if` in loops 3. **Always provide initial value to `reduce`** — avoids errors 4. **Use `find` over `filter[0]`** — more efficient ## Common Mistakes 1. **Forgetting `return` in `map`/`filter`** — arrow functions with `{}` need explicit `return` 2. **Mutating original array** — these methods return new arrays 3. **Missing initial value in `reduce`** — causes errors on empty arrays 4. **Using `forEach` to return values** — it always returns `undefined`
No changes yet
Reset to original
Submit suggestion
cancel