Skip to main content

Arrays and their Methods

An Array is a special variable that can hold more than one value at a time. In JavaScript, arrays are incredibly flexible: they can grow in size dynamically and mix different data types.

They are defined using square brackets [].

const fruits = ["Apple", "Banana", "Orange"];
const mixed = ["Text", 42, true, null];

// Accessing (0-indexed based)
console.log(fruits[0]); // Apple

Mutable Methods (Change the original array)

  • push(): Adds one or more elements to the end of the array.
  • pop(): Removes and returns the last element of the array.
  • unshift(): Adds one or more elements to the beginning.
  • shift(): Removes and returns the first element.
const cart = [];
cart.push("Shoes"); // ["Shoes"]
cart.push("Shirt"); // ["Shoes", "Shirt"]
const last = cart.pop(); // Returns "Shirt". cart is now ["Shoes"]

⭐️ The Functional Trinity: map, filter, reduce

In modern JavaScript, you will rarely use traditional for loops. Instead, we use pure functional methods that do not modify the original array, but return a completely new array.

These methods pair perfectly with implicit return Arrow Functions.

1. .map() (Transform)

Executes the same function on each element of the array and returns a new array of the same size with the results.

const numbers = [1, 2, 3];
// "Map each number and convert it into number * 2"
const doubles = numbers.map(number => number * 2);

console.log(doubles); // [2, 4, 6]
console.log(numbers); // [1, 2, 3] (The original remains intact)

2. .filter() (Filter)

Examines each element and returns a new array containing only the elements that pass a condition (that return true).

const ages = [15, 22, 12, 30, 18];
// "Filter the array, keeping only ages greater than or equal to 18"
const adults = ages.filter(age => age >= 18);

console.log(adults); // [22, 30, 18]

3. .reduce() (Reduce / Accumulate)

It is the most complex. It executes a "reducer" function on each element, returning a single value (not an array) as a result. It requires an "accumulator" and the "current value", plus an initial value.

const prices = [10, 20, 30];

// Sum the entire cart:
// 1st iteration: total (0) + price (10) = 10
// 2nd iteration: total (10) + price (20) = 30
// 3rd iteration: total (30) + price (30) = 60
const totalToPay = prices.reduce((total, price) => total + price, 0);
// ^ initial total value

console.log(totalToPay); // 60