Loading

T4 JavaScript · Lesson 5

Arrays

Keeping many values in one ordered list: making and reading arrays, changing them with push, pop and splice, finding items, slicing and joining, why two names can share one array, and sorting numbers and words the right way.

  • make an array, and read any item by its index, from the front or the back
  • add, remove and replace items with push, pop, shift, unshift and splice
  • find an item with indexOf, includes, find and findIndex
  • take part of an array with slice, join arrays, and turn arrays into text and back
  • say when two names share one array, and make a real copy
  • sort numbers and words correctly with a compare function
About 65 minutesChecked against Node.js on the laptop (the kit runs every code block with it) 22.23.1 (2026-11-06)Play this lesson's games

The back cover

A shop does not keep one variable for each item on its shelves. It keeps a list: a price list, a list of orders, a queue of customers. Code needs the same thing, one name for many values kept in order, and that is an array.

These pages show how to make an array and read it by position, and how to change it at either end or in the middle. They find items, take parts out and join them into text. They explain why two names can share one array, and how to sort numbers so that 10 comes after 9.

Before you start

The story: A timetable out of order

The tram board in the Clock Tower square lists the day's departures, one under another. This morning it reads 10.15, 11.40, 7.05, 8.30, 9.50, and the early passengers stand at the stop wondering where the 7.05 went. On Friday someone added a late tram to the Sunday board, and it appeared on the weekday board as well.

Master Hakim Verge spreads the board's script across his bench. Every departure is kept in one list, and the list is put in order each morning before the board is painted.

"A list is a row of boxes," he says. "Find out what order the script thinks it is putting them in. And find out how many boards are looking at the same row."

A shopping list, a class register, a tram timetable and a cricket team's batting order all have the same shape: many values of one kind, in an order that matters. Keeping each value in a name of its own, item1, item2, item3, falls apart at the fourth item. JavaScript keeps such a list in one value, called an array. This lesson shows how to make one, read it, change it, search it, cut it, share it and sort it.

It builds on these ideas. Each one has a tiny example, so you can check that you remember it.

What you already knowA tiny exampleWhere it comes back
Indexes from 0."Pune"[0] gives P.Every item of an array has an index.
length."Pune".length gives 4.An array has a length too.
at(-1)."Pune".at(-1) gives e.The last item of an array.
slice and indexOf."Masala chai".slice(0, 6)Arrays have methods of the same names.
Strings never change.A method gives a new string.Arrays can change, which is new.
Copying a value.let b = a; copies a number.An array is shared, not copied.
const.const rate = 18;A const array can still change inside.
Callbacks.(x, y) => x - yfind and sort take one.
Strings compared by their codes."2" > "12" is true.Why the default sort gets numbers wrong.
typeof.typeof {} gives object.An array is an object too.

By the end of this lesson you will be able to:

  • make an array, and read any item by its index, from the front or the back;
  • add, remove and replace items with push, pop, shift, unshift and splice;
  • find an item with indexOf, includes, find and findIndex;
  • take part of an array with slice, join arrays, and turn arrays into text and back;
  • say when two names share one array, and make a real copy;
  • sort numbers and words correctly with a compare function.

How to follow this lesson

Every block on this page runs. console.log prints an array in square brackets, with strings in single quotes, so you can see each item and its type at a glance. When an array is not what you expect, print it whole, just before and just after the line that should change it.

In one line

An array keeps many values in one ordered list, each at an index counted from 0.

Making an array, and reading it

At a glance

A railway reservation chart lists passengers in order, seat by seat, and the clerk reads it by number: seat 1, seat 2, seat 3. An array is such a chart: an ordered list of values kept under one name.

An array is written in square brackets, and its items are read by index, counted from 0. The last item is at(-1), or the one at length minus 1, and length gives the count. An index past the end gives undefined, and Array.isArray tells an array apart from other objects.

Take a guess: What does an array give back for an index past its last item?

A class register is a numbered list of names: roll number 1, roll number 2, and so on. The teacher can read any name by its number, count how many there are, or go down the list in order. An array is a register for values.

Array

A value that holds an ordered list of values, written between square brackets and separated by commas: ["mango", "banana", "guava"]. Each value in it is an item or element.

const fruits = ["mango", "banana", "guava"];
console.log(fruits, fruits.length, fruits[0], fruits[2], fruits[3]);
[ 'mango', 'banana', 'guava' ] 3 mango guava undefined

console.log prints the whole array in square brackets, with its strings in single quotes. fruits.length is 3, the number of items. Each item has an index, counted from 0 exactly as the characters of a string are: mango at 0, banana at 1, guava at 2. Read fruits[0] aloud as "fruits at 0". Index 3 is past the end, and gives undefined, with no error.

The last item is at index length − 1. As with strings, at with a negative number counts from the back, while square brackets do not: inside them, −1 is not an index at all, and gives undefined.

const list = ["a", "b", "c"];
console.log(list.at(-1), list[list.length - 1], list[-1]);
c c undefined

Any values, any mix

An array can hold values of any type, and can mix them. It can even hold other arrays. In practice most arrays hold one kind of value, a list of prices or a list of names, because code that reads them can then treat every item the same way.

const mixed = [42, "chai", true, null, [1, 2]];
console.log(mixed.length, typeof mixed, Array.isArray(mixed), Array.isArray("abc"));
5 object true false

The values lesson said that an array is a kind of object, and typeof agrees: it says object. To ask whether a value is an array, use Array.isArray(...), which gives true only for arrays.

const empty = [];
console.log(empty, empty.length, empty[0]);
[] 0 undefined

An empty array, written [], has length 0, and every index gives undefined. Many lists start empty and grow, as the next section shows.

Arrays of arrays

A cinema's seats are rows of seats; a times table is rows of numbers. An array whose items are arrays holds such a grid. The first index picks the row, and the second picks the item in that row:

const grid = [[1, 2, 3], [4, 5, 6]];
console.log(grid[1][2], grid.length, grid[0].length);
6 2 3

Read grid[1][2] from the left: grid[1] is the second row, [4, 5, 6], and its item at index 2 is 6. grid has 2 rows, and each row has 3 items.

Worked example 1

A cricket team's batting order lists its first five batters: Rohit, Shubman, Virat, Shreyas and Rahul. Make the array, and print the opener, the number of batters, and the fifth batter in two ways.

What we have: five names in order

What we need: the first name, the count, and the fifth name

The plan: the opener is at index 0; the fifth is at index 4, which is also length − 1

const order = ["Rohit", "Shubman", "Virat", "Shreyas", "Rahul"];
console.log(order[0], order.length, order[4], order.at(-1));
Rohit 5 Rahul Rahul
  1. The fifth batter is at index 4, because counting starts at 0, and at(-1) reaches the same item from the back.

It prints Rohit 5 Rahul Rahul.

Check: five items have indexes 0 to 4, so the last index is 5 − 1 = 4.

A path that fails: writing order[5] for the fifth batter. It gives undefined, with no error, and a scorecard that prints undefined at number five.

Worked example 2

A school keeps each section's marks in a row: section A scored 72, 85 and 90, and section B scored 64, 78 and 88. Read the second mark of section B.

What we have: a grid with one row for each section

What we need: the second mark of the second row

The plan: the row comes first, then the place in the row, both counted from 0

const marks = [[72, 85, 90], [64, 78, 88]];
console.log(marks[1][1], marks[1]);
78 [ 64, 78, 88 ]
  1. marks[1] is section B's row; [1] inside it is the second mark.

Section B's second mark is 78.

Check: the row printed alongside shows 78 in the middle.

A path that fails: writing marks[2][2], counting from 1. There is no row 2, so marks[2] is undefined, and reading [2] from undefined stops the program with a TypeError.

When you are stuck: an item comes out as undefined

Indexes start at 0: the last item is at length − 1.

A negative number works only with at(-1), not inside square brackets.

Print the whole array to see what it really holds, and how long it is.

In a grid, check the order: the row's index comes first.

Your turn

const days = ["Mon", "Tue", "Wed"];
console.log(days[1], days.length, days[days.length - 1], days[3]);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
Tue 3 Wed undefined
  1. Index 1 is the second item: Tue.
  2. There are 3 items.
  3. The last is at index 2: Wed.
  4. Index 3 is past the end: undefined.

It prints Tue 3 Wed undefined.

What do typeof [] and Array.isArray([]) give?Tap to reveal
  1. An array is a kind of object, so typeof says object.
  2. Array.isArray asks the exact question, and says true.

object and true.

Make an array of the seasons summer, monsoon and winter, and print the middle one.Tap to reveal
const seasons = ["summer", "monsoon", "winter"];
console.log(seasons[1]);
monsoon

The middle item is at index 1: monsoon.

Did you know?

An object underneath

An array is an object underneath. The standard calls it an exotic object that gives special treatment to array index property keys, the 0, 1 and 2 of its items. That is why typeof [] says object, the same as for any object. It is also why Array.isArray exists: typeof alone cannot tell an array from other objects.

Why it fits here: It explains this topic's last tool: Array.isArray is needed because, to typeof, every array looks like any other object.

Sources: ECMAScript Language Specification: Array Exotic Objects; MDN: typeof

The longest list

An array cannot grow for ever. MDN explains that its length is an unsigned, 32-bit integer, so an array holds at most 4,29,49,67,295 items. Its own example sets a length of 232, which is 4,29,49,67,296, and gets a RangeError: Invalid array length. Memory runs out long before that, so the limit lives mostly in the standard.

Why it fits here: It puts a number on this topic's length: a count kept in 32 bits, which is far more than any page will need.

Sources: MDN: Array length; ECMAScript Language Specification: Array Exotic Objects

In one line

An array is an ordered list in square brackets. Read an item by its index from 0, the last with at(-1) or [length − 1], and the count with length; an index past the end gives undefined, and Array.isArray tells an array apart from other objects.

Changing an array

At a glance

A shopping list on the fridge changes all day: milk is crossed out, eggs are added at the bottom, and bread is squeezed in near the top. An array can be changed in the same ways, because arrays are mutable.

Assign to an index to replace an item. The methods push and pop work at the end, unshift and shift at the front, and splice anywhere in the middle. The method push gives back the new length, while pop and shift give back the item they removed.

Take a guess: What does push give back after it adds an item?

Strings never change; their methods give back new strings. Arrays are different. An array can be changed in place: an item replaced, an item added at the end, an item taken from the front. A value that can be changed in place is called mutable, and changing it is called mutating it.

Replacing an item

Assign to an index, and the item there is replaced:

const marks = [72, 85, 90];
marks[1] = 88;
console.log(marks);
[ 72, 88, 90 ]

Assigning far past the end works too, but leaves gaps, which JavaScript calls empty items. The length jumps to one more than the index used. Gaps cause trouble later, so add items with the methods below instead.

const list = ["a", "b"];
list[5] = "f";
console.log(list, list.length);
[ 'a', 'b', <3 empty items>, 'f' ] 6

Adding and removing at the ends

MethodWhat it doesWhat it gives back
push(x)adds x at the endthe new length
pop()removes the last itemthe item removed
unshift(x)adds x at the frontthe new length
shift()removes the first itemthe item removed
const cart = ["rice"];
console.log(cart.push("dal"), cart.push("oil", "salt"), cart);
2 4 [ 'rice', 'dal', 'oil', 'salt' ]

push can add several items at once, in order, and gives back the new length: 2 after the first push, 4 after the second. That return value surprises people, who expect the array itself. The array was changed in place; the length is only a report.

const cart = ["rice", "dal", "oil"];
const last = cart.pop();
console.log(last, cart, cart.length);
oil [ 'rice', 'dal' ] 2

A queue at a ticket window works from the front: the first to arrive is the first served. shift takes the first item off, and unshift puts one in front of the rest:

const queue = ["Asha", "Ravi"];
queue.unshift("Meera");
const first = queue.shift();
console.log(first, queue);
Meera [ 'Asha', 'Ravi' ]

Meera was put at the front, and then served first, leaving Asha and Ravi. A way to remember the four: push and pop work at the end, like a pile of plates; shift and unshift work at the front, where every other item must shift along.

Changing the middle: splice

splice(start, count, ...items) is the one method that works anywhere. It removes count items from index start, puts any further items in their place, and gives back the removed items as an array:

const days = ["Mon", "Tue", "Wed", "Thu", "Fri"];
const removed = days.splice(1, 2);
console.log(removed, days);
[ 'Tue', 'Wed' ] [ 'Mon', 'Thu', 'Fri' ]
const days = ["Mon", "Thu"];
days.splice(1, 0, "Tue", "Wed");
console.log(days);
[ 'Mon', 'Tue', 'Wed', 'Thu' ]

In the second block, the count is 0, so nothing is removed, and the two new items go in at index 1. splice is powerful but easy to misread, since one call can remove and insert at once. Read each call aloud: "from index 1, remove 0, insert Tue and Wed".

A common mistake

Expecting push to give back the array. const bigger = cart.push("salt"); puts the new length, a number, into bigger. The array to use is cart itself, which push has already changed.

Worked example 3

A kirana shop's order list starts with rice and dal. The customer adds oil, then decides against the dal, then wants sugar at the very top of the list. Make each change and print the list.

What we have: the list rice, dal

What we need: the list sugar, rice, oil

The plan: push for the end, splice for the middle, unshift for the front

const order = ["rice", "dal"];
order.push("oil");
order.splice(1, 1);
order.unshift("sugar");
console.log(order);
[ 'sugar', 'rice', 'oil' ]
  1. After push: rice, dal, oil. splice(1, 1) removes one item at index 1, the dal. unshift puts sugar first.

The list is sugar, rice, oil.

Check: three changes, and three items left, in the order the customer asked for.

A path that fails: writing order.pop() to remove the dal. pop removes the last item, which by then is the oil.

When you are stuck: an array did not change the way you expected

Print the array just before and just after the line.

Check which end the method works at: push and pop at the end, shift and unshift at the front.

Read a splice call aloud: from which index, remove how many, insert what.

Remember what each method gives back: push a length, pop and shift an item, splice an array of removed items.

Your turn

const stack = ["a", "b", "c"];
stack.pop();
stack.push("d");
console.log(stack, stack.length);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
[ 'a', 'b', 'd' ] 3
  1. pop removes c.
  2. push adds d at the end.
  3. Three items remain.

It prints [ 'a', 'b', 'd' ] 3.

What does ["x"].push("y") give back, and why?Tap to reveal
  1. push changes the array in place.
  2. It gives back the new length, which is 2.

It gives 2, the new length.

Using splice, replace the second item of ["tea", "milk", "sugar"] with coffee.Tap to reveal
const items = ["tea", "milk", "sugar"];
items.splice(1, 1, "coffee");
console.log(items);
[ 'tea', 'coffee', 'sugar' ]

items.splice(1, 1, "coffee"): from index 1, remove 1, insert coffee.

Did you know?

A sailor's word

The method splice is named after a sailor's craft. Rope splicing is the forming of a semi-permanent joint between two ropes, or two parts of one rope, by partly untwisting and then interweaving their strands. The method does the same to an array: it opens the list at a place, takes some items out and weaves new ones in.

Why it fits here: It gives this topic's hardest method a picture to remember: splice opens the list, removes strands and weaves in new ones.

Sources: Wikipedia: Rope splicing; Wiktionary: splice

A twin that leaves the list alone

Changing an array in place can surprise the code that shares it, so splice now has a twin. The method toSpliced() is the copying version of the splice() method: it returns a new array with some elements removed or replaced, and the original stays as it was. MDN shows it working across browsers since July 2023.

Why it fits here: It gives this topic's changes a safer form: when other code shares the array, change a copy instead of the list itself.

Sources: MDN: Array.prototype.toSpliced(); ECMAScript Language Specification: Array.prototype.toSpliced

In one line

Arrays are mutable: assign to an index to replace an item, push and pop at the end, unshift and shift at the front, and splice anywhere. The method push gives back the new length, while pop and shift give back the item removed.

Finding items

At a glance

Before buying, a shopper scans the shelf: is the rice brand here, and if so, where? Arrays answer both questions, whether an item is there, and at which position. Both are asked every day: is this student on the list, and at which roll number?

The method includes asks whether an item is there, and indexOf asks where, giving -1 when it is not there and 0 for the first item. The methods find and findIndex take a test as a callback, and stop at the first item that passes it.

Take a guess: What does indexOf give back when the item is not in the array?

A shopkeeper asked for oil looks along the shelf until the oil turns up, then reaches for it. Sometimes the question is "is there any oil?", sometimes "which shelf is it on?", and sometimes "show me the first bottle under ₹200". Arrays have a method for each of these questions.

MethodThe question it answersWhat it gives back
includes(x)is x in the array?true or false
indexOf(x)where is the first x?its index, or −1
lastIndexOf(x)where is the last x?its index, or −1
find(test)which is the first item that passes the test?the item, or undefined
findIndex(test)where is the first item that passes the test?its index, or −1
const stock = ["rice", "dal", "oil", "dal"];
console.log(stock.indexOf("dal"), stock.lastIndexOf("dal"), stock.indexOf("salt"), stock.includes("oil"));
1 3 -1 true

dal is first at index 1 and last at index 3. salt is not there, so indexOf gives −1, which can never be a real index. includes gives a plain yes or no. When you only need to know whether an item is there, includes says so most directly.

A common mistake

Testing the result of indexOf as a true-or-false value. if (stock.indexOf("rice")) is false for rice, because rice is at index 0, and 0 is falsy, while −1, for an item that is missing, is truthy. Compare with −1, as in stock.indexOf("salt") !== -1, or use includes.

Finding by a test: find and findIndex

indexOf and includes look for an item that is exactly equal, by ===. To find the first item that passes a test, such as "more than ₹100", give find a callback. find calls it with each item in turn, and stops at the first item for which it returns a truthy value:

const prices = [120, 45, 300, 80];
console.log(prices.find((p) => p > 100), prices.findIndex((p) => p > 100), prices.find((p) => p > 500));
120 0 undefined

The first price over 100 is 120, at index 0; 300 is never reached, as find stops at the first match. No price is over 500, so that find gives undefined. This is the callback idea of the functions lesson at work: find knows how to walk the array, and your small arrow knows what you are looking for.

One difference with NaN

indexOf compares with ===, and NaN is not equal even to itself, so [NaN].indexOf(NaN) is −1. includes uses a slightly different rule that treats NaN as equal to NaN, so [NaN].includes(NaN) is true. Both results are measured in the block below.

console.log([NaN].includes(NaN), [NaN].indexOf(NaN));
true -1

Worked example 4

A school's list of students who paid the trip fee is Asha, Ravi and Meera. Check whether Ravi and Kiran have paid, and find Ravi's place in the list.

What we have: the list of names who paid

What we need: yes or no for two names, and Ravi's index

The plan: includes for the yes or no, indexOf for the place

const paid = ["Asha", "Ravi", "Meera"];
console.log(paid.includes("Ravi"), paid.includes("Kiran"), paid.indexOf("Ravi"));
true false 1

Ravi has paid, at index 1; Kiran has not.

Check: Ravi is the second name, which is index 1.

A path that fails: checking if (paid.indexOf("Asha")) to see whether Asha paid. Asha is at index 0, which is falsy, so the program decides that she has not paid.

Worked example 5

A delivery app has the distances in kilometres of today's orders: 3, 12, 7 and 15. Find the first order over 10 km, and its place in the list.

What we have: four distances

What we need: the first distance over 10, and its index

The plan: find and findIndex, each with the test (km) => km > 10

const distances = [3, 12, 7, 15];
console.log(distances.find((km) => km > 10), distances.findIndex((km) => km > 10));
12 1

The first long order is 12 km, at index 1.

Check: 3 is not over 10; 12 is, and it comes second, at index 1. 15 is never reached.

Another way: if the question were "is any order over 10 km?", distances.some((km) => km > 10) gives a plain true; the loops lesson meets some and its partner every.

When you are stuck: a search does not find an item that is there

indexOf and includes compare with ===: check the type and capitals of what you search for.

Remember that indexOf gives −1, not false, for a missing item, and 0 for the first item.

For a test, such as a price range, use find or findIndex with a callback.

Print the array and the value you search for, side by side, with typeof.

Your turn

const colours = ["red", "green", "blue", "green"];
console.log(colours.indexOf("green"), colours.includes("pink"), colours.find((c) => c.length > 4));
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
1 false green
  1. The first green is at index 1.
  2. pink is not there.
  3. The first colour longer than 4 characters is green.

It prints 1 false green.

Why is if (["tea", "coffee"].indexOf("tea")) { ... } a bug?Tap to reveal
  1. tea is at index 0.
  2. 0 is falsy, so the block does not run, although tea is there.

indexOf gives 0, which is falsy; use includes("tea").

Find the first even number in [7, 9, 4, 6].Tap to reveal
console.log([7, 9, 4, 6].find((n) => n % 2 === 0));
4

4, the first item for which the test is true.

Did you know?

Two searches, one disagreement

The methods includes and indexOf can disagree about one value. MDN explains that includes compares items using the SameValueZero algorithm, which works like === except that NaN is considered equal to itself. The method indexOf uses strict equality, so it always returns -1 when looking for NaN. So [1, 2, NaN].includes(NaN) is true, while indexOf cannot find NaN at all.

Why it fits here: It shows why this topic offers both methods: includes answers yes or no reliably, even for NaN, while indexOf gives a position.

Sources: MDN: Array.prototype.includes(); MDN: Array.prototype.indexOf(); ECMAScript Language Specification: Keyed Collections

A faster way to ask is it there

For a list you search often, a Set is faster than an array. The standard requires Set objects to give access times that are sublinear on the number of elements, so a lookup does not check every item in turn. MDN notes that Set's has method is, on average, faster than Array.prototype.includes when both hold the same number of items.

Why it fits here: It adds a next step to this topic: includes checks items one by one, so a long list searched again and again belongs in a Set.

Sources: ECMAScript Language Specification: Set Objects; MDN: Set

In one line

includes asks whether an item is there; indexOf asks where, giving −1 when it is not, and 0 for the first item. find and findIndex take a test as a callback and stop at the first item that passes.

Taking parts, joining, and turning into text

At a glance

A tailor cuts a length from a roll of cloth and leaves the roll as it was. Some array methods work the same way: they give back a new array and leave the original alone.

The methods slice and concat give back new arrays, while splice changes the original. The method join turns an array into text, with the separator you give, and split turns text into an array. Knowing which methods change the original, and which do not, saves many bugs.

Take a guess: Does slice change the array it is called on?

Some methods change an array in place, as the last two sections showed. Others leave it as it was, and give back something new. Knowing which kind a method is matters as much as knowing what it does.

slice: a part, as a new array

slice(start, end) gives back a new array of the items from index start up to, but not including, index end, exactly as slice does for strings. A negative number counts from the end. The original array is not touched:

const nums = [10, 20, 30, 40, 50];
console.log(nums.slice(1, 3), nums.slice(-2), nums);
[ 20, 30 ] [ 40, 50 ] [ 10, 20, 30, 40, 50 ]

Two names that sound alike, slice and splice, do very different jobs. A way to tell them apart: splice has an extra letter, because it does extra: it changes the array. slice only looks.

slice(start, end)splice(start, count, ...items)
changes the array?noyes
gives backa new array of the partan array of the removed items
the second number iswhere to stophow many to remove

concat: two arrays into one

const a = [1, 2];
const b = [3, 4];
console.log(a.concat(b), a, b);
[ 1, 2, 3, 4 ] [ 1, 2 ] [ 3, 4 ]

concat gives a new array with the items of both; a and b are unchanged. The modern JavaScript step shows a shorter way to join arrays, with three dots.

join and split: arrays and text

join(separator) turns an array into one string, with the separator between the items. split(separator), a string method, goes the other way, cutting a string into an array at each separator:

const names = ["Asha", "Ravi", "Meera"];
console.log(names.join(", "), names.join(" and "), names.join(""));
Asha, Ravi, Meera Asha and Ravi and Meera AshaRaviMeera
console.log("Pune,Mumbai,Nagpur".split(","), "chai".split(""));
[ 'Pune', 'Mumbai', 'Nagpur' ] [ 'c', 'h', 'a', 'i' ]

Splitting on the empty string cuts a string into its single characters. The methods join and split are how programs read and write simple lists in text: a line of a spreadsheet saved as text, or tags typed into a box with commas.

An array that is put where text is needed, as in a template literal or joined to a string with +, is turned into text with commas between the items and no spaces. Use join when the separator matters:

const items = ["pen", "book"];
console.log(`Items: ${items}`, `Items: ${items.join(", ")}`);
Items: pen,book Items: pen, book

Worked example 6

A form has a box where a teacher types the subjects of a class, separated by commas: Maths,Science,English. Turn it into an array, add Hindi, and show the subjects as a sentence with commas and spaces.

What we have: the text Maths,Science,English

What we need: the line Subjects: Maths, Science, English, Hindi

The plan: split the text at the commas, push the new subject, then join with a comma and a space

const typed = "Maths,Science,English";
const subjects = typed.split(",");
subjects.push("Hindi");
console.log(`Subjects: ${subjects.join(", ")}`);
Subjects: Maths, Science, English, Hindi

It prints Subjects: Maths, Science, English, Hindi.

Check: four subjects, with a comma and a space between each pair.

A path that fails: joining with join() and no separator. join's default separator is a comma with no space, so it prints Maths,Science,English,Hindi, as cramped as the box the teacher typed into.

When you are stuck: a part or a join comes out wrong

slice's second number is where to stop, and that item is not included.

If the original array changed, you used splice, not slice.

Give join the separator you want; without one, it uses a comma with no space.

If text was cut in the wrong places, print the separator you gave split, between brackets.

Your turn

const word = ["c", "h", "a", "i"];
console.log(word.join(""), word.slice(1).join("-"));
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
chai h-a-i
  1. join with the empty string puts the letters together: chai.
  2. slice(1) takes from index 1 to the end: h, a, i, and join puts dashes between them.

It prints chai h-a-i.

After const a = [1, 2, 3]; const b = a.slice(0, 2);, what are a and b?Tap to reveal
  1. slice gives a new array of indexes 0 and 1, stopping before 2.
  2. a is not changed.

a is [1, 2, 3] and b is [1, 2].

Turn the text Delhi-Agra-Jaipur into an array of three cities.Tap to reveal
console.log("Delhi-Agra-Jaipur".split("-"));
[ 'Delhi', 'Agra', 'Jaipur' ]

split("-") cuts at each dash: three cities.

Did you know?

The method that broke the web

Naming an array method can break old websites. In 2018, a method called Array.prototype.flatten turned out to be web-incompatible: shipping it in Firefox Nightly broke at least one popular website, because the widespread MooTools library used the same name. The proposal's author jokingly suggested smoosh as a new name. In the end, flatten was renamed to flat.

Why it fits here: It shows what this topic's array methods carry: every new name must avoid the names that old pages already gave arrays.

Source: Chrome for Developers: #SmooshGate FAQ

Arrays turn into commas

An array turned into text gets commas. The standard's toString for arrays just calls join, and join, when no separator is given, separates the items with a comma. So `${[1, 2, 3]}` gives 1,2,3, the same as [1, 2, 3].join(). To get spaces or anything else, call join yourself with the separator you want.

Why it fits here: It explains a surprise around this topic's join: an array placed in a template literal arrives with commas and no spaces.

Sources: ECMAScript Language Specification: Array.prototype.toString; MDN: Array.prototype.join()

In one line

slice and concat give back new arrays and leave the original alone, while splice changes it. join turns an array into text with the separator you give, and split turns text into an array.

Two names, one array

At a glance

Two flatmates share one fridge. If one of them eats the last mango, the other finds it gone, because there was only ever one fridge. Two names can share one array in the same way.

A name holds a reference to an array, so assigning it, or passing it to a function, shares the one array, and a change through any name shows through all. Copy it with slice() when you need a separate array. A const keeps the reference fixed, not the items.

Take a guess: If b = a and then b.push(4), does a change too?

Write a friend's address on a slip of paper and hand it over, and your friend now knows where the house is. There is still only one house. If your friend paints the front door blue, you will find a blue door when you visit. Arrays are passed around like that address.

A name that holds a number holds the number itself, so assigning it to another name copies the number, as the values lesson showed. A name that holds an array holds a reference to it: the way to find the one array kept in the computer's memory. Assigning it to another name copies the reference, not the array.

Reference

What a name holds for an array or other object: the way to find one array in memory. Two names holding the same reference share one array, and a change made through either name shows through both.

const a = [1, 2, 3];
const b = a;
b.push(4);
console.log(a, b, a === b);
[ 1, 2, 3, 4 ] [ 1, 2, 3, 4 ] true

There was only ever one array. b is a second name for it, so the push through b shows through a too. And === between two arrays asks "are these the same array?", not "do these hold the same items?", so it gives true here.

This is the trap of the tram board: the Sunday board's list was the weekday list under a second name, so a tram added for Sunday appeared on every day.

Making a real copy

To get a second array with the same items, make a new array. slice() with no numbers gives a copy of the whole array:

const a = [1, 2, 3];
const c = a.slice();
c.push(4);
console.log(a, c, a === c);
[ 1, 2, 3 ] [ 1, 2, 3, 4 ] false

Now a and c are two arrays. Changing c leaves a alone, and === says they are not the same array. The same rule means that two arrays made separately are never equal by ===, however alike their items:

console.log([1, 2] === [1, 2], String([1, 2]) === String([1, 2]));
false true

To compare the items of two simple arrays, compare their text forms, as the second answer does, or compare them item by item, which the loops lesson shows. Copies made with slice are shallow: an array of arrays is copied one level deep, so the inner rows are still shared. The objects lesson comes back to deeper copies.

const does not freeze an array

const promises that a name will always hold the same reference, not that the array behind it will never change. So a const array can be changed in place, but the name cannot be given a different array:

const cart = ["rice"];
cart.push("dal");
console.log(cart);
[ 'rice', 'dal' ]
const cart = ["rice"];
cart = ["dal"];
Uncaught TypeError: Assignment to constant variable.
    at line 2

This is why most arrays in modern code are made with const: the name always means this one list, and the list can still grow and shrink.

Functions receive the reference

Passing an array to a function passes its reference, so the parameter is a second name for the caller's array. A function that mutates its parameter mutates the caller's array:

function addItem(list, item) {
  list.push(item);
}
const cart = ["rice"];
addItem(cart, "dal");
console.log(cart);
[ 'rice', 'dal' ]

Sometimes that is the job. Often it is a surprise, called a side effect in the functions lesson. A function that returns a new array instead leaves the caller's array alone, and says what it does in its name: withItem(list, item) that returns list.concat([item]).

Worked example 7

A tram company keeps the weekday departures, in minutes after midnight, as [425, 510, 590]. Sunday has the same trams plus a late one at 1380. Make the Sunday list without changing the weekday list.

What we have: the weekday list, and one extra departure for Sunday

What we need: a Sunday list with four departures, and the weekday list still with three

The plan: copy the weekday list with slice, then push the late tram onto the copy

const weekday = [425, 510, 590];
const sunday = weekday.slice();
sunday.push(1380);
console.log(weekday, sunday);
[ 425, 510, 590 ] [ 425, 510, 590, 1380 ]
  1. slice made a new array, so the push changed only Sunday's.

Sunday has four departures, and the weekday list still has three.

Check: a === check between the two lists gives false: they are two arrays.

A path that fails: writing const sunday = weekday;. It looks like a copy, and the late tram then appears on the weekday board too, as it did in the story.

When you are stuck: an array changed when you did not change it

Look for a second name for it: a line such as const b = a; shares, and does not copy.

Look for a function that received it and mutates it with push, pop, splice or sort.

Make a copy with slice() before changing an array that someone else also uses.

Remember that === between arrays asks whether they are the same array, not whether they look alike.

Your turn

const x = [1, 2];
const y = x;
const z = x.slice();
y.push(3);
console.log(x.length, y.length, z.length);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
3 3 2
  1. y is a second name for x's array, so the push shows in both: 3 and 3.
  2. z is a copy made before the push: 2.

It prints 3 3 2.

Why does const list = []; list.push(1); work, when const n = 0; n = 1; does not?Tap to reveal
  1. const forbids giving the name a new value.
  2. push changes the array the name refers to; the name still holds the same reference.

Because push changes the array, not the name.

What does [] === [] give, and why?Tap to reveal
  1. Each [] makes a new, separate array.
  2. === between arrays asks whether they are the same array.

false: two separate arrays.

Did you know?

A copy all the way down

Copying with slice() makes a new outer array, but the objects inside are still shared. For a full copy, browsers have offered structuredClone() across the board since March 2022. MDN explains that it creates a deep clone of a value using the structured clone algorithm, so nested arrays and objects are copied too, and the copy shares nothing with the original.

Why it fits here: It finishes this topic's lesson on sharing: slice() copies one level, while structuredClone() copies every level.

Sources: MDN: structuredClone(); WHATWG: HTML Standard, Structured data

Freezing, one level deep

A const keeps the name fixed, not the items, but an array can be frozen. MDN explains that freezing an object prevents extensions and makes existing properties non-writable, so a frozen array's items cannot be changed, added or removed. It also warns that the freeze is shallow: arrays and objects inside a frozen array can still change.

Why it fits here: It answers this topic's question about const: when the items themselves must not change, freeze the array.

Sources: MDN: Object.freeze(); ECMAScript Language Specification: Object.freeze

In one line

A name holds a reference to an array, so assigning it, or passing it to a function, shares the one array; a change through any name shows through all. Copy with slice() when you need a separate array; const keeps the reference fixed, not the items.

Putting an array in order

At a glance

A teacher arranging marks from lowest to highest compares numbers, not the shapes of the digits. JavaScript's sort, left to itself, compares the shapes: it orders items as text. A list of marks sorted that way puts 100 before 25.

So sort with no compare function puts 10 before 9, and numbers need a compare function, (x, y) => x - y. The methods sort and reverse change the array in place, while toSorted gives back a sorted copy and leaves the original alone.

Take a guess: Why does [10, 9, 1].sort() give [1, 10, 9]?

A teacher sorting answer sheets by marks, or a librarian shelving books by title, compares two items at a time and decides which goes first. Arrays have a method that does this for you, sort, and it has one famous surprise.

const nums = [10, 9, 1, 100];
nums.sort();
console.log(nums);
[ 1, 10, 100, 9 ]

With nothing in its brackets, sort turns every item into text and orders the texts character by character, as the conditionals lesson compared strings. As text, "10" and "100" start with 1, which comes before 9, so they go before "9". The numbers are in dictionary order, not in order of size. This is the trap of the tram board, whose times came out as 10.15 before 7.05.

A compare function

To sort numbers by size, give sort a callback that compares two items. The method sort calls it with two items, a and b, again and again, and reads the answer: a negative number means a goes first, a positive number means b goes first, and 0 means either order will do.

Compare function

A callback that sort calls with two items and that returns a number: negative to put the first item first, positive to put the second first, zero to leave them as they are. (x, y) => x - y sorts numbers from smallest to largest.

const nums = [10, 9, 1, 100];
nums.sort((x, y) => x - y);
console.log(nums);
nums.sort((x, y) => y - x);
console.log(nums);
[ 1, 9, 10, 100 ]
[ 100, 10, 9, 1 ]

Why does x - y work? If x is smaller, x − y is negative, so x goes first: smallest first. Swapping them, y - x, turns every answer around, and sorts from largest to smallest.

Sorting words

The default sort suits words better, but capitals still come before small letters, because their character codes are smaller:

const names = ["ravi", "Asha", "meera"];
console.log(names.sort(), names);
[ 'Asha', 'meera', 'ravi' ] [ 'Asha', 'meera', 'ravi' ]

Two things show here. Asha comes first because capital A has a smaller code than every small letter. And sort changed names itself, and gave back the same array, as both printed values show. For names in a real app, localeCompare compares by the rules of a language, capitals and accents included; the modern JavaScript step meets it again.

Sorting without changing the original

sort, like reverse, works in place. When the original order must be kept, sort a copy, or use toSorted, a newer method that gives back a sorted copy and leaves the array alone:

const nums = [3, 1, 2];
const sorted = nums.toSorted((x, y) => x - y);
console.log(sorted, nums);
[ 1, 2, 3 ] [ 3, 1, 2 ]
const nums = [1, 2, 3];
nums.reverse();
console.log(nums);
[ 3, 2, 1 ]
MethodChanges the array?Gives back
sort(compare)yesthe same array, sorted
reverse()yesthe same array, reversed
toSorted(compare)noa new, sorted array

Worked example 8

The tram board's departures are kept as minutes after midnight: 615, 700, 425, 510, 590. Sort them, then show them as times such as 7.05.

What we have: five departures as numbers of minutes

What we need: the departures in order, written as hours and minutes

The plan: sort the numbers with a compare function, then turn each into hours and minutes with Math.floor and %

const times = [615, 700, 425, 510, 590];
times.sort((x, y) => x - y);
const first = times[0];
console.log(times, `${Math.floor(first / 60)}.${String(first % 60).padStart(2, "0")}`);
[ 425, 510, 590, 615, 700 ] 7.05
  1. 425 minutes is 7 hours (420 minutes) and 5 minutes, written 7.05 with the minutes padded to two digits.

The order is 425, 510, 590, 615, 700, and the first tram is at 7.05.

Check: the five times in order are 7.05, 8.30, 9.50, 10.15 and 11.40, the board of the story.

A path that fails: keeping the times as the strings "10.15", "7.05" and so on, and calling sort(). As text, 10.15 comes before 7.05, which is the board the passengers found that morning.

When you are stuck: a sort comes out in a strange order

Numbers sorted with no compare function are sorted as text. Add (x, y) => x - y.

If capitals come first, the sort compared character codes. Bring the words to one case first, or use localeCompare.

If the original order was lost, sort changed the array in place. Sort a copy, or use toSorted.

Print the array just before the sort, to check that its items are the type you think.

Your turn

const scores = [40, 5, 300];
console.log(scores.toSorted(), scores.toSorted((a, b) => a - b));
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
[ 300, 40, 5 ] [ 5, 40, 300 ]
  1. With no compare function, the numbers are sorted as text: 300, 40, 5, by their first characters 3, 4 and 5.
  2. With a - b, they are sorted by size.

It prints [ 300, 40, 5 ] [ 5, 40, 300 ].

Sort [18, 3, 27] from largest to smallest.Tap to reveal
console.log([18, 3, 27].sort((a, b) => b - a));
[ 27, 18, 3 ]

(a, b) => b - a gives 27, 18, 3.

After const a = [2, 1]; const b = a.sort();, is a still [2, 1]?Tap to reveal
  1. sort works in place, and gives back the same array.
  2. So a is now [1, 2], and b is a second name for it.

No: a is [1, 2]; sort changed it.

Did you know?

Stable since Chrome 70

Sorting is stable now: items that compare as equal keep their original order. The standard says so in plain terms, i.e., the sort is stable. It was not always so in Chrome. V8's team describes moving to a stable algorithm and making sort stable in V8 v7.0, Chrome 70. So you can sort by name and then by date, and items with the same date stay in name order.

Why it fits here: It makes this topic's compare function safer to chain: sort by one key, then another, and equal items keep the first order.

Sources: ECMAScript Language Specification: SortIndexedProperties; V8: Getting things sorted in V8

A sort from Python

Chrome sorts arrays with an algorithm borrowed from another language. V8's team chose Timsort, initially developed by Tim Peters for Python in 2002, and describes it as an adaptive stable Mergesort variant. It looks for so-called runs, stretches of the list that are already in order, which real lists often have, such as marks entered in roughly rising order.

Why it fits here: It shows what runs behind this topic's sort: one well-studied algorithm, shared by languages, doing the comparing you supply.

Source: V8: Getting things sorted in V8

In one line

sort with no compare function orders items as text, so numbers need (x, y) => x - y. sort and reverse change the array in place; toSorted gives back a sorted copy and leaves the original alone.

Where it is used

Almost every list a program shows or keeps is an array. Here is where each idea of this lesson shows up in real work.

What you learnedWhere it is usedA real example
an array and its indexesevery list on a screenthe items in a shopping cart; the stops on a bus route
push and poplists that grow and shrink at one endthe undo history of an editor: each change pushed, each undo popped
shift and unshiftqueuesorders waiting at a restaurant's kitchen, served first come, first served
splicechanging the middle of a listremoving one song from the middle of a playlist
includes, indexOf, findsearchingchecking whether a PIN code is in the list of places a shop delivers to
slice, join and splittext in and outa line of a CSV file split into fields; tags joined for display
references and copieskeeping data safe from other codea function that sorts a copy, so the caller's list keeps its order
sort with a compare functionevery sorted tableproducts by price, students by marks, trains by departure time
arrays of arraysgrids and tablesthe seats of a cinema hall; the cells of a spreadsheet

Mistakes and debugging

These are the slips that people meet most often with arrays. Every output below is the real one, from the code shown.

1. Counting from 1

const order = ["Rohit", "Shubman", "Virat"];
console.log(order[3]);
undefined

No error: index 3 is past the end. The fix: the last item is at length − 1, or use at(-1).

2. Testing indexOf as true or false

const stock = ["rice", "dal"];
console.log(stock.indexOf("rice") ? "found" : "missing");
missing

No error: rice is at index 0, which is falsy. The fix: stock.includes("rice").

3. Sorting numbers with no compare function

console.log([10, 9, 1, 100].sort());
[ 1, 10, 100, 9 ]

No error: the numbers were sorted as text. The fix: sort((x, y) => x - y).

4. A second name taken for a copy

const weekday = [425, 510];
const sunday = weekday;
sunday.push(1380);
console.log(weekday);
[ 425, 510, 1380 ]

No error: both names share one array. The fix: weekday.slice() makes a real copy.

5. Using what push gives back as the array

const cart = ["rice"];
const bigger = cart.push("dal");
console.log(bigger);
2

No error: push gives back the new length. The fix: keep using cart, which push changed in place.

6. Mixing up slice and splice

const nums = [10, 20, 30, 40];
nums.splice(1, 2);
console.log(nums);
[ 10, 40 ]

No error: splice removed two items from the array itself. The fix: to look at a part without changing anything, use nums.slice(1, 3).

7. Reassigning a const array

const cart = ["rice"];
cart = ["dal"];
Uncaught TypeError: Assignment to constant variable.
    at line 2

The fix: change the array in place, with push, splice or cart.length = 0 to empty it, or make the name with let if it must hold a different array.

8. Reading a row that is not there

const marks = [[72, 85], [64, 78]];
console.log(marks[2][1]);
Uncaught TypeError: Cannot read properties of undefined (reading '1')
    at line 2

The fix: rows are counted from 0 too, so the second row is marks[1].

The debugging corner: print the whole array

When an array misbehaves, print it whole, just before and just after the line that should change it. The console.log line shows every item, with strings in quotes and holes as empty items, so a wrong type, a missing item or an extra one shows at once. For an array that changed by itself, search the code for every name it was assigned to, and every function it was passed to.

Quick card

The whole lesson on one card. Come back to it whenever you need a reminder.

The lesson in code

// make and read: indexes from 0; at(-1) for the last
const order = ["Rohit", "Shubman", "Virat"];
console.log(order[0], order.length, order.at(-1));

// change in place: push/pop at the end, unshift/shift at the front, splice anywhere
order.push("Rahul");
order.splice(1, 1);
console.log(order);

// find: includes, indexOf (-1 when missing), find with a test
console.log(order.includes("Virat"), order.indexOf("Kiran"), [3, 12, 7].find((n) => n > 5));

// new arrays, original untouched: slice, concat; text: join, split
console.log(order.slice(0, 2), "a,b".split(","), order.join(", "));

// share or copy: b = a shares; a.slice() copies
const a = [1, 2];
const b = a;
const c = a.slice();
b.push(3);
console.log(a, c);

// sort numbers with a compare function
console.log([10, 9, 1, 100].sort((x, y) => x - y));
Rohit 3 Virat
[ 'Rohit', 'Virat', 'Rahul' ]
true -1 12
[ 'Rohit', 'Virat' ] [ 'a', 'b' ] Rohit, Virat, Rahul
[ 1, 2, 3 ] [ 1, 2 ]
[ 1, 9, 10, 100 ]
When you seeIt meansLook at
undefined from an indexan index past the end, or counting from 1the last index is length − 1
an item that is there reported missingindexOf's 0 taken as falseincludes
numbers in dictionary ordersort with no compare function(x, y) => x - y
a list that changed by itselftwo names, or a function, sharing one arrayslice() for a copy
a number where an array was expectedthe length that push gives backthe array itself
TypeError: Assignment to constant variable.a const array given a new arraychange it in place, or use let
Cannot read properties of undefineda row or item that is not therethe indexes, from 0

The story: Every tram in its place

You find that the script was ordering the times as text, character by character, so 10.15 came before 7.05. You keep each time as minutes after midnight, a number, and order the numbers. Then you find that the Sunday board held no list of its own, only a second name for the weekday list, so you give it a copy.

The board repaints itself: 7.05, 8.30, 9.50, 10.15, 11.40. The late tram appears on Sunday only.

Master Verge counts the boards in the square. "One row for each," he says, "unless they truly mean to share."

Reagents gathered: array, index, push, slice, sort, reference.

Sources