30 April 2026

JavaScript Array

 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.

JavaScript
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.

JavaScript
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."

JavaScript
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.

JavaScript
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).

JavaScript
const names = ['Alice', 'Bob'];
names.forEach(name => console.log(`Hello, ${name}!`));

Quick Comparison Table

MethodReturnsPurpose
.map()New ArrayTransform every element.
.filter()New ArraySelect a subset of elements.
.find()Single ValueGet the first match.
.reduce()Single ValueBoil the array down to one result.
.forEach()undefinedRun code for each item (no return).

No comments:

Post a Comment

Comments Welcome

Finding duplicate records in SQL Server

 Finding duplicate records in SQL Server 1. The GROUP BY and HAVING Method This is the most standard approach. It is best used when you on...