Array Methods

JavaScript arrays come with built-in methods to manipulate, transform, and access data easily. Understanding these methods is essential for efficient coding.

Illustration of array_methods
Illustration of array_methods

💡 What Are Array Methods?

Functions attached to array objects that allow you to perform common operations like adding, removing, searching, or transforming elements.

Common Array Methods Overview

Array Methods & Their Purpose
MethodPurpose
push()Adds elements to the end of an array
pop()Removes the last element
shift()Removes the first element
unshift()Adds elements to the beginning
map()Creates a new array by transforming each element
filter()Creates a new array with elements that pass a test
reduce()Reduces array to a single value by accumulating
forEach()Executes a function on each element (no return)
find()Returns the first element that matches a condition
includes()Checks if an array contains a value
slice()Returns a shallow copy of a portion of the array
splice()Adds/removes elements at a specific index
sort()Sorts elements in place

Examples of Key Array Methods

📌 Deep Dive: map() vs forEach()

JAVASCRIPT
const numbers = [1, 2, 3, 4];

// map returns a new array with values doubled
const doubled = numbers.map(num => num * 2);

// forEach just runs a function on each element, no return
numbers.forEach(num => console.log(num * 2));
Output
doubled: [2, 4, 6, 8]
console logs: 2, 4, 6, 8 (each on new line)

📌 Deep Dive: filter() to Get Specific Items

JAVASCRIPT
const words = ['apple', 'banana', 'cherry', 'date'];

// Get words longer than 5 characters
const longWords = words.filter(word => word.length > 5);
Output
longWords: ['banana', 'cherry']

📌 Deep Dive: reduce() to Sum Values

JAVASCRIPT
const values = [10, 20, 30];

// Sum all values
const total = values.reduce((acc, current) => acc + current, 0);
Output
total: 60

Mutating vs Non-Mutating Methods

Some array methods change the original array, while others return a new array without modifying the original.

Mutation Behavior of Common Methods
MethodMutates Original Array?
push()Yes
pop()Yes
shift()Yes
unshift()Yes
splice()Yes
sort()Yes
map()No
filter()No
reduce()No
slice()No

⚠️ Be Careful with Mutations

Mutating methods change the original array, which can cause bugs if the original data is needed later. Prefer non-mutating methods when immutability is important.

Summary

  • push(), pop(), shift(), and unshift() are used to add or remove elements at the ends.
  • map(), filter(), and reduce() are powerful for transforming, selecting, and accumulating data.
  • Know if a method mutates the original array or returns a new one to avoid unintended side effects.

💡 Tip

Try combining methods like filter() and map() to perform complex operations in a clean, readable way.