An array is an ordered list of values kept in one variable: a list of names, a set of marks, the items in a shopping cart. Each value sits at a numbered position called an index, starting from 0. JavaScript arrays grow and shrink as needed and come with built-in methods such as map(), filter() and reduce() that replace many hand-written loops.
In this lesson you will learn
- Creating arrays and reading items by index
- Adding and removing items with
push,pop,shiftandunshift - Searching with
includes,indexOfandfind - Transforming data with
map,filterandreduce - Sorting numbers correctly
Creating and Changing Arrays
const colors = ["red", "green", "blue"];
console.log(colors[0], colors[colors.length - 1], colors.length);
colors.push("yellow"); // add to the end
colors.unshift("black"); // add to the start
console.log(colors);
const last = colors.pop(); // remove from the end
const first = colors.shift(); // remove from the start
console.log(last, first, colors);
console.log(colors.includes("green"), colors.indexOf("blue"));
console.log(colors.slice(0, 2)); // copy part of the array
console.log(colors.join(" | "));
Output
red blue 3
[ 'black', 'red', 'green', 'blue', 'yellow' ]
yellow black [ 'red', 'green', 'blue' ]
true 2
[ 'red', 'green' ]
red | green | blue
- Write arrays with square brackets.
colors[0]is the first item andcolors[colors.length - 1]is the last. push()andpop()work at the end;unshift()andshift()work at the start.pop()andshift()return the item they removed.includes()answers yes or no;indexOf()gives the position, or-1if the item is missing.slice(start, end)copies part of the array without changing it; the end index is not included.join()turns the array into one string with a separator.
map, filter, reduce and sort
const marks = [72, 45, 88, 39, 91, 60];
const curved = marks.map((m) => m + 5);
const passed = marks.filter((m) => m >= 50);
const total = marks.reduce((sum, m) => sum + m, 0);
const firstHigh = marks.find((m) => m > 85);
const allPositive = marks.every((m) => m > 0);
console.log("curved:", curved);
console.log("passed:", passed);
console.log("average:", (total / marks.length).toFixed(1));
console.log("first above 85:", firstHigh, "| all positive:", allPositive);
console.log([10, 9, 100, 1].sort()); // text order!
console.log([10, 9, 100, 1].sort((a, b) => a - b)); // numeric order
Output
curved: [ 77, 50, 93, 44, 96, 65 ]
passed: [ 72, 88, 91, 60 ]
average: 65.8
first above 85: 88 | all positive: true
[ 1, 10, 100, 9 ]
[ 1, 9, 10, 100 ]
map()builds a new array by applying a function to every item.filter()builds a new array with only the items for which the function returns true.reduce()combines all items into one value. Heresumstarts at0and each mark is added to it.find()returns the first matching item;every()andsome()test whether all or any items match.- By default
sort()compares items as text, so100comes before9. Pass a compare function,(a, b) => a - b, to sort numbers. Note thatsort()changes the original array.
Array Method Cheat Sheet
| Method | Returns | Changes original? |
|---|---|---|
push, unshift | New length | Yes |
pop, shift | Removed item | Yes |
splice(i, n) | Removed items | Yes |
sort, reverse | The same array | Yes |
slice, concat | New array | No |
map, filter | New array | No |
reduce, find, join | A single value | No |
forEach | undefined | No |
Common Mistakes
- Reading
arr[arr.length], which is one past the end and givesundefined. - Sorting numbers without a compare function.
- Expecting
map()to change the original; it returns a new array that you must store. - Comparing arrays with
===:[1] === [1]is false because they are two different objects.
Practice Exercises
Exercise 1. From [3, 8, 12, 5, 20], make a new array of only the even numbers, each doubled.
Show answer
const result = [3, 8, 12, 5, 20].filter((n) => n % 2 === 0).map((n) => n * 2);
console.log(result); // [16, 24, 40]
Exercise 2. Find the largest number in an array using reduce().
Show answer
const nums = [14, 3, 27, 9];
const max = nums.reduce((best, n) => (n > best ? n : best), nums[0]);
console.log(max); // 27
Frequently Asked Questions
How do I copy an array?
Use the spread syntax, const copy = [...original];, or original.slice(). Both make a shallow copy: nested objects are still shared.
How do I remove duplicates from an array?
Convert it to a Set and back: const unique = [...new Set(arr)];.
Summary
- Arrays hold ordered values; indexes start at 0 and
lengthgives the size. push/popandunshift/shiftadd and remove at the ends.map,filterandreducetransform data without changing the original.- Sort numbers with
sort((a, b) => a - b).
Next: JavaScript Objects.
