Arrays: The Basics + Core Methods

An array is an ordered list — a single variable that holds many values, each with its own numbered position.

What Is an Array?

const fruits = ["apple", "banana", "cherry"];

An array stores an ordered list of values inside square brackets [ ], separated by commas. Each value has a numbered index, starting at 0 — not 1.

Index012
Value"apple""banana""cherry"
fruits[0]; // "apple"
fruits[2]; // "cherry"
fruits.length; // 3
🚂 Real-life analogy

An array is like a numbered train with carriages. Carriage #0 is the first one, not #1. You can walk straight to any carriage by its number, add new carriages to the front or back, or count how many carriages there are in total.

Why Do We Use Arrays?

Whenever you have a list of related things — a to-do list, a list of users, a shopping cart — an array keeps them together, in order, under one variable name, instead of scattering them across dozens of separate variables.

Adding and Removing Items

MethodWhat it doesChanges original?
push(x)Add x to the endYes
pop()Remove and return the last itemYes
unshift(x)Add x to the beginningYes
shift()Remove and return the first itemYes
splice(start, count)Remove/insert items anywhereYes
slice(start, end)Copy out a portion, leaving original untouchedNo
const nums = [1, 2, 3];
nums.push(4);     // [1, 2, 3, 4]
nums.pop();       // removes 4  → [1, 2, 3]
nums.unshift(0);  // [0, 1, 2, 3]
nums.shift();     // removes 0  → [1, 2, 3]

Note on vocabulary: "mutating" means changing the original array in place. push, pop, shift, unshift, and splice all mutate. slice does not — it returns a brand new array.

Looping and Transforming: map, filter, find

const prices = [10, 20, 30];

const withTax = prices.map(p => p * 1.1);
// [11, 22, 33] — a NEW array, one output per input

const expensive = prices.filter(p => p > 15);
// [20, 30] — a NEW array with only the matching items

const firstBig = prices.find(p => p > 15);
// 20 — the first matching VALUE, not an array
  • map — "transform every item," always returns an array of the same length
  • filter — "keep only the items that pass a test," returns a possibly-shorter array
  • find — "give me the first item that passes a test," returns a single value or undefined

Combining Values: reduce

const total = prices.reduce((sum, price) => sum + price, 0);
// 60 — boils the whole array down to one value

reduce walks through the array carrying an "accumulator" (sum) forward, combining it with each item, and starting from the value you provide last (0).

Checking Contents

[1,2,3].includes(2);        // true
[1,2,3].some(n => n > 2);  // true — at least one matches
[1,2,3].every(n => n > 0); // true — ALL match

Copying a Portion: slice()

const fruits = ["apple", "banana", "cherry", "date"];

fruits.slice(1, 3);  // ["banana", "cherry"] — from index 1 up to (not including) 3
fruits.slice(2);     // ["cherry", "date"] — from index 2 to the end
fruits.slice(-2);    // ["cherry", "date"] — last 2 items (negative counts from end)
fruits.slice();      // shallow copy of the entire array — original untouched
  • slice(start, end) — returns a new array from start up to but not including end
  • Negative indexes count backward from the end: -1 is the last item, -2 is second-to-last, etc.
  • slice() with no arguments is the standard way to make a shallow copy of an array
  • The original array is never changed — slice always returns a brand new array

Combining Arrays: concat()

const a = [1, 2];
const b = [3, 4];

a.concat(b);               // [1, 2, 3, 4] — merges two arrays into a new one
a.concat(b, [5, 6]);       // [1, 2, 3, 4, 5, 6] — can merge any number of arrays
a.concat(99);              // [1, 2, 99] — non-array values are just appended as items

concat() does not mutate either array — it returns a brand new merged array. The modern spread alternative ([...a, ...b]) is also common and equally valid.

Converting to String: join() and toString()

const words = ["apple", "banana", "cherry"];

words.join(", ");   // "apple, banana, cherry"
words.join(" | ");  // "apple | banana | cherry"
words.join("");    // "applebananacherry" — no separator
words.join();     // "apple,banana,cherry" — default separator is a comma

words.toString(); // "apple,banana,cherry" — same as join() with no argument, less flexible

join() is the go-to for turning an array into a human-readable string — you control exactly what goes between each item. toString() is a quick fallback that always uses commas and can't be customized.

Finding Positions: indexOf() and lastIndexOf()

const nums = [10, 20, 30, 20, 10];

nums.indexOf(20);         // 1 — index of the FIRST time 20 appears
nums.lastIndexOf(20);     // 3 — index of the LAST time 20 appears
nums.indexOf(99);         // -1 — not found; always check for -1 before using the result
nums.indexOf(10, 1);      // 4 — start searching from index 1 onwards

Both use strict equality (===) for comparison, so they work well for primitives (numbers, strings) but won't match objects by their content — only by identity. Use findIndex() when you need a custom test condition.

Creating Arrays: Array.of() and Array.from()

// Array.of() — creates an array from any number of arguments, exactly as given
Array.of(1, 2, 3);        // [1, 2, 3]
Array.of(7);             // [7]   ← note: NOT an empty 7-slot array like new Array(7) would be!
new Array(7);           // [ , , , , , , ] — 7 empty slots (a common footgun)

// Array.from() — turns any iterable or array-like into a real array
Array.from("hello");            // ["h", "e", "l", "l", "o"]
Array.from({ length: 3 }, (_, i) => i); // [0, 1, 2] — build a range
Array.from(new Set([1, 2, 2, 3])); // [1, 2, 3] — deduplicate via Set then convert back

Array.from() is the standard way to convert anything iterable (strings, Sets, Maps, DOM NodeLists) into a genuine array with all the normal methods available.

Common Mistakes

⚠ Watch out for
  • Forgetting that map/filter/slice return new arrays — the original array is untouched unless you reassign it.
  • Forgetting arrays are zero-indexed — the last item is at array.length - 1, not array.length.
  • Using sort() on numbers without a compare function — by default it sorts as text, so [10, 2, 1].sort() gives [1, 10, 2], not [1, 2, 10].

Best Practices

  • Prefer non-mutating methods (map, filter, slice) when you can — they avoid accidental side effects.
  • Give sort() a compare function whenever sorting numbers: arr.sort((a, b) => a - b).
  • Use find when you want one item, filter when you want several.

Performance Notes

push/pop at the end of an array are fast. unshift/shift at the beginning are slower on large arrays because every other item has to shift position. For very large lists where you frequently add/remove from the front, consider alternate data structures.

Browser Compatibility

push, pop, concat, join, indexOf, lastIndexOf, slice, toString have existed since the earliest versions of JavaScript. map, filter, reduce, find, some, every arrived in ES5/ES6 (2009–2015). Array.of() and Array.from() are ES6 (2015). Newer immutable methods like toSorted() and with() (2023) need a fairly modern browser.

Interview Questions

What's the difference between map and forEach?

map returns a brand new array built from the return value of the callback on each item, while forEach just runs the callback for its side effects and always returns undefined.

What's the difference between slice and splice?

slice copies out a section of an array without changing the original. splice changes the original array in place, and can both remove and insert items at a given position.

✏️ Exercise

Given const nums = [3, 7, 1, 9, 4], use filter to get only numbers greater than 4, then use reduce to add them together.

🧠 Quiz

1. What index does the first item in an array have?

0.

2. Does filter() change the original array?

No — it returns a new array and leaves the original untouched.

🚀 Mini Challenge

Given a list of names, use map to create a new array where each name is uppercase, without changing the original list.

Summary

  • Arrays store ordered lists of values, indexed from 0; access items with array[index] and check length with .length.
  • push/pop/splice mutate; slice/concat/map/filter always return new arrays.
  • join() converts an array to a string; indexOf()/lastIndexOf() find positions of values.
  • reduce combines an entire array down to a single value; Array.of() and Array.from() create arrays safely.

Related Topics

MDN reference: developer.mozilla.org → JavaScript → Array (placeholder — add live link)