PROGRAMMING-CONCEPTS

Array Methods: Syntax, Usage, and Examples

Array methods are built-in tools that help you transform, search, and summarize lists of values without writing manual loops. They make code easier to read and let you express what you want to do with data instead of micro-managing every index.


How Array Methods Work

In JavaScript and TypeScript, array methods are functions you call on arrays, and you pass another function (a callback) that describes the operation for each element. That callback usually receives the current item, its index, and the whole array, but most of the time you only need the item itself.

Under the hood, the array method handles the iteration. You just provide the logic, such as “multiply each number,” “keep only even values,” or “find the first item that matches a condition.”


Core Array Methods and What They Do

map – Transform Each Item

const prices = [10, 15, 20];
const withTax = prices.map(price => price * 1.2);

This goes through each price, applies a 20% increase, and returns a new array [12, 18, 24]. The original prices array stays the same because map never mutates it.

const names = ["kai", "mira", "luca"];
const capitalized = names.map(name => name[0].toUpperCase() + name.slice(1));

This transforms each lowercase name into a capitalized version, returning a new array of nicely formatted names. Again, no changes happen to the original list.

You can think of map as “same length, different content” — perfect for data transformation.


filter – Keep Only Certain Items

const scores = [95, 40, 88, 72, 100];
const passing = scores.filter(score => score >= 70);

This checks each score and keeps only those greater than or equal to 70, returning a new array of passing results. The scores that don’t meet the condition are simply left out.

const emails = ["test@example.com", "", "user@site.dev"];
const nonEmpty = emails.filter(email => email !== "");

This removes empty strings so you only keep valid-looking entries. filter is your go-to choice for cleaning up data and removing unwanted items.


reduce – Combine Everything into One Value

const steps = [3000, 7000, 5000];
const totalSteps = steps.reduce((sum, current) => sum + current, 0);

This walks through the array and keeps a running total, ending with a single number equal to the sum of all steps. The 0 at the end is the starting value for sum, which makes the function safe even for empty arrays.

const tags = ["js", "html", "css"];
const csv = tags.reduce((joined, tag, index) => {
  return index === 0 ? tag : joined + ", " + tag;
}, "");

This builds a comma-separated string out of the array items. reduce shines whenever you’re summarizing an array into one value: totals, strings, objects, or even other collections.


find – Get the First Matching Item

const products = [
  { id: 1, stock: 0 },
  { id: 2, stock: 3 },
  { id: 3, stock: 5 }
];

const firstAvailable = products.find(product => product.stock > 0);

This scans the array until it finds the first product with stock above zero, then returns that object. If nothing matches, find returns undefined, which you can check for later.

const cities = ["Paris", "Madrid", "Berlin", "Lisbon"];
const found = cities.find(city => city.startsWith("B"));

This returns "Berlin" because it’s the first city whose name starts with "B". Use find when you care about a single item, not all items that match.


some – Does At Least One Item Match?

const logs = [200, 201, 500, 404];
const hasServerError = logs.some(code => code >= 500);

This returns true because at least one status code is 500 or higher. some stops checking once it finds a match, which makes it efficient for quick checks.

const passwords = ["short", "BetterPass1", "ok"];
const anyStrong = passwords.some(pw => pw.length >= 10);

This checks whether any password in the list meets the length requirement. It’s a good fit for “does any element satisfy this rule?” type questions.


every – Do All Items Match?

const ages = [22, 31, 19];
const allAdults = ages.every(age => age >= 18);

This returns true because every age is 18 or above. If even one value fails the test, every returns false.

const filenames = ["report.pdf", "notes.pdf", "table.pdf"];
const allPdf = filenames.every(name => name.endsWith(".pdf"));

This checks whether the whole list uses the same file extension. every works well for validations where every element must meet a condition.


Chaining Array Methods

One of the strongest patterns with array methods is chaining, where you connect multiple operations in a row. This lets you build a data pipeline that reads from left to right.

const readings = [12, 5, 18, 3, 20];

const processed = readings
  .filter(n => n >= 10)          // keep only readings 10 or higher
  .map(n => n * 2)               // double those readings
  .reduce((sum, n) => sum + n, 0); // sum them up

This first filters out small readings, then doubles the remaining ones, then totals them into a single number. You can read the chain step by step without thinking about manual indices or temporary arrays.

const names = ["  ivy", "Noah ", "  elio  "];

const cleanNames = names
  .map(name => name.trim())         // trim whitespace
  .filter(name => name.length > 0)  // remove empty results
  .map(name => name[0].toUpperCase() + name.slice(1)); // capitalize

This pipeline trims whitespace, removes empty strings, and capitalizes each name. Chaining lets you keep all related transformations in one place instead of scattering them across multiple loops.


forEach vs map

Both forEach and map run through all items in an array, but they are used for different purposes.

const items = ["pasta", "rice", "bread"];

items.forEach(item => {
  console.log(item.toUpperCase());
});

Here forEach is used to perform a side effect — logging to the console — and it does not return a useful value. You use it when you want to “do something” with each item, such as updating the DOM or sending data somewhere.

const uppercased = items.map(item => item.toUpperCase());

This produces a new array with transformed values and leaves the original array unchanged. map is meant for transformation where the resulting array matters and side effects are avoided.

You can think of the distinction like this:

  • use forEach when your goal is side effects and you don’t need a result array
  • use map when your goal is a new, transformed array and you do want the result

Parallels in Python and Swift

Even though the syntax differs, Python and Swift follow similar ideas.

prices = [10, 15, 20]
with_tax = [p * 1.2 for p in prices]

This Python list comprehension plays the same role as map in JavaScript by producing a new list with transformed values. It’s a concise way to express “for each item, create a new value.”

let scores = [95, 40, 88, 72, 100]
let passing = scores.filter { $0 >= 70 }

This Swift code uses filter to keep only passing scores, just like the JavaScript version. These parallels help you move between languages while relying on the same mental model.


Common Mistakes and How to Avoid Them

A few pitfalls show up often when working with array methods:

  • Using map when you don’t use the returned array, which wastes work and makes intent unclear
  • Forgetting the initial value in reduce, which can cause errors when the array is empty
  • Expecting find to return an index instead of an item (for that, you’d use findIndex in JS)
  • Mutating external state inside map or filter, which can make code harder to reason about

Sticking to the idea “transform with map, filter with filter, summarize with reduce, and use forEach only for side effects” keeps your code predictable.


Summary

Array methods like map, filter, reduce, find, some, and every give you a powerful toolkit for working with lists of data. They help you express complex operations through small, focused callbacks and clean method chains instead of tangled loops. Once you get comfortable with these patterns, data-heavy tasks in JavaScript, TypeScript, Python, and Swift become simpler, clearer, and less error-prone.

Learn to Code for Free
Start learning now
button icon
To advance beyond this tutorial and learn to code by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

Reach your coding goals faster