10 JavaScript Array Methods Every Coder Should Know

 

🔟 JavaScript Array Methods Every Coder Should Know

JavaScript arrays are powerful, but many developers—especially beginners—only use the basic .push() and .pop(). Let's unlock the full power of arrays with 10 essential methods every JavaScript coder should know.


1. .map() – Transform Each Element

Transforms every element in the array and returns a new array.

const numbers = [1, 2, 3]; const doubled = numbers.map(num => num * 2); console.log(doubled); // [2, 4, 6]

2. .filter() – Keep What You Need

Filters the array based on a condition.

const scores = [50, 85, 95, 40]; const passed = scores.filter(score => score >= 60); console.log(passed); // [85, 95]

3. .reduce() – Collapse Into One Value

Reduces an array to a single value (sum, average, object, etc.).

const nums = [1, 2, 3, 4]; const sum = nums.reduce((acc, curr) => acc + curr, 0); console.log(sum); // 10

4. .forEach() – Loop Without Returning

Executes a function for each array element (no return value).

const fruits = ['🍎', '🍌', '🍇']; fruits.forEach(fruit => console.log(fruit));

5. .find() – Find the First Match

Returns the first element that satisfies a condition.

const users = [{id: 1}, {id: 2}]; const user = users.find(u => u.id === 2); console.log(user); // {id: 2}

6. .some() – At Least One Match?

Returns true if at least one element matches a condition.

const ages = [13, 25, 17]; const hasAdult = ages.some(age => age >= 18); console.log(hasAdult); // true

7. .every() – All Must Match

Returns true only if all elements match a condition.

const temps = [72, 75, 78]; const isComfortable = temps.every(t => t > 70); console.log(isComfortable); // true

8. .includes() – Quick Existence Check

Checks if an element exists in the array.

const pets = ['dog', 'cat', 'bird']; console.log(pets.includes('cat')); // true

9. .sort() – Sort Alphabetically or Numerically

Sorts array elements (be careful—modifies the original array).

const nums = [10, 2, 30]; nums.sort((a, b) => a - b); console.log(nums); // [2, 10, 30]

10. .slice() – Extracts Section of an Array

Returns a shallow copy of a portion of an array into a new array object, selected from start to end (end not included). The original array is not modified.

Syntax:

javascript
array.slice(start, end)

Example:

const fruits = ['apple', 'banana', 'cherry', 'date']; const citrus = fruits.slice(1, 3); console.log(citrus); // ['banana', 'cherry']

Use Cases:

  • Cloning an array: const copy = arr.slice()

  • Extracting a subarray

  • Creating immutable state in functional programming


🚀 Final Tip:

These methods can be chained to write elegant, readable code:

const result = [1, 2, 3, 4] .filter(n => n % 2 === 0) .map(n => n * 10); console.log(result); // [20, 40]

💬 Your Turn!

What’s your favorite JavaScript array method? Did you learn something new today? Comment below!

Post a Comment

0 Comments