Arrays in JavaScript

The array methods that replace loops — map, filter, find, reduce — and which ones change the original.

5 minute read · Free · Taught properly in our Front End Development Training in Amritsar

An array is an ordered list. Same indexing rules as most languages: it starts at zero.

const marks = [88, 72, 95, 61];
marks[0];           // 88
marks.length;       // 4
marks.at(-1);       // 61 — last item

The four methods worth learning first

// map — same length, each item transformed
const doubled = marks.map(m => m * 2);        // [176, 144, 190, 122]

// filter — the items that pass a test
const good = marks.filter(m => m >= 80);      // [88, 95]

// find — the first match, or undefined
const first = marks.find(m => m < 70);        // 61

// reduce — everything down to one value
const total = marks.reduce((sum, m) => sum + m, 0);   // 316

Each takes a function and runs it on every item. Once these are comfortable, most for loops in your code disappear, and what is left reads like a description of what you wanted rather than a list of steps.

Which ones change the original

This catches people out, so learn the split:

Return something new, original untouched: map, filter, slice, concat, join, toSorted

Change the array in place: push, pop, shift, unshift, splice, sort, reverse

const original = [3, 1, 2];
const sorted = original.sort();
// original is now [1, 2, 3] too — sort changed it

If that matters, copy first: [...original].sort().

The sort surprise

[10, 9, 100].sort();     // [10, 100, 9]

Not a bug. sort() converts items to strings by default, and "100" sorts before "9". For numbers, pass a comparison:

[10, 9, 100].sort((a, b) => a - b);    // [9, 10, 100]

Copying

const a = [1, 2, 3];
const b = a;          // same array, two names
b.push(4);            // a is [1,2,3,4] as well

const c = [...a];     // a real copy

The spread ... copies one level deep. An array of objects copied this way still shares the objects inside it.

Stuck on this in your own code?

That is what a class is for. Sit one for free at WebPrims on Majitha Road, Amritsar — write some JavaScript, ask the mentor why yours is not working, and decide afterwards.