JavaScript Array
JavaScript array methods are essential tools for writing clean, functional code. Instead of using for loops to manually move data around, these methods allow you to transform and filter arrays with much less syntax.
Think of them as a pipeline where your data goes in, gets processed, and comes out the other side.
1. .map() — The Transformer
Use this when you want to perform the same action on every item in an array. It returns a new array of the same length.
Logic: "Do X to every item."
Example: Doubling numbers.
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8]
2. .filter() — The Decider
Use this when you want to keep only the items that meet a specific condition. It returns a new array, usually shorter than the original.
Logic: "Keep only items that are true for X."
Example: Getting only even numbers.
const numbers = [1, 2, 3, 4, 5, 6];
const evens = numbers.filter(num => num % 2 === 0);
console.log(evens); // [2, 4, 6]
3. .find() — The Searcher
Similar to filter, but it stops as soon as it finds one match. It returns the value of the first element, not an array.
Logic: "Give me the first item that matches X."
const users = [{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}];
const user = users.find(u => u.id === 2);
console.log(user.name); // "Bob"
4. .reduce() — The Accumulator
This is the "Swiss Army Knife." It takes an entire array and condenses it down into a single value (like a sum, a string, or even an object).
Logic: "Combine all items into one result."
Example: Summing an array.
const prices = [10, 20, 30];
const total = prices.reduce((accumulator, current) => accumulator + current, 0);
console.log(total); // 60
5. .forEach() — The Worker
This method doesn't return anything. It simply executes a function for each item. Use it when you want to produce a "side effect" (like logging to the console or updating a database).
const names = ['Alice', 'Bob'];
names.forEach(name => console.log(`Hello, ${name}!`));
Quick Comparison Table
| Method | Returns | Purpose |
| .map() | New Array | Transform every element. |
| .filter() | New Array | Select a subset of elements. |
| .find() | Single Value | Get the first match. |
| .reduce() | Single Value | Boil the array down to one result. |
| .forEach() | undefined | Run code for each item (no return). |
No comments:
Post a Comment
Comments Welcome