SyntaxPilot
Courses/JavaScript/Lesson 7

JavaScript · Lesson 7 of 40 · 14 min

Arrays and array methods

queued

These are the notes for JavaScript episode 7. You will learn why one variable per value doesn't scale, how to create an array, why indexes start at 0, length and the last item, what happens past the end, looping over an array, push, pop, shift and unshift, why a const array can still change, searching with includes and indexOf, cutting and copying with splice and slice, the sort() trap and its fix, copying vs sharing an array, and a few handy methods (join, reverse, at, split, Array.isArray). Every example runs as-is in the SyntaxPilot compiler (language: JavaScript, Node.js).

Why arrays: Ravi's order book

Ravi's chai stall gets orders all day: ₹120, ₹80, ₹250. His app should keep them, print them and add them up. With what we knew, the obvious way is one variable per order, and a loop from episode 6 to print them:

let order1 = 120;
let order2 = 80;
let order3 = 250;
for (let i = 1; i <= 3; i++) {
  console.log(order + i);
}
ReferenceError: order is not defined

JavaScript looked for a variable named order, on its own, and there isn't one. A variable name is fixed when you write the code: you can't glue a number onto a name while the program runs. So no loop can reach order1, order2, order3, and a thousand orders would mean a thousand variables typed by hand. We need one name for the whole list, and a number to pick each item. That is an array.

Arrays and indexes: a train with numbered coaches

A train In JavaScript Meaning
One train name (the Rajdhani) const orders = [ ... ] one name for the whole list
Coach numbers, counted from the engine orders[0], orders[1] the index: position, starting at 0
How many coaches orders.length the number of items

An array is an ordered list of values written in square brackets [ ], separated by commas. Each value is an element (or item). Its position is its index, and the first index is 0: the first coach behind the engine is zero steps away from it.

const orders = [120, 80, 250];
console.log(orders);
console.log(orders[0]);
console.log(orders[2]);
console.log(orders.length);
console.log(orders[orders.length - 1]);
console.log(orders[3]);
[ 120, 80, 250 ]
120
250
3
250
undefined
  • orders[0] is the first item, orders[2] the third.
  • orders.length is 3, so the last item is always at orders.length - 1.
  • orders[3] doesn't exist: JavaScript gives undefined, with no error. Many languages crash here; JavaScript doesn't, so a wrong index becomes a silent bug.
 index:   0     1     2
        [120] [80] [250]      length = 3, last index = length - 1 = 2

Looping over an array (and the <= length bug)

const orders = [120, 80, 250];
for (let i = 0; i <= orders.length; i++) {
  console.log(`Order ${i + 1}: Rs ${orders[i]}`);
}
Order 1: Rs 120
Order 2: Rs 80
Order 3: Rs 250
Order 4: Rs undefined

A customer who never existed! That's episode 6's off-by-one error: indexes go from 0 to length - 1, so the check must be <, not <=.

const orders = [120, 80, 250];
for (let i = 0; i < orders.length; i++) {
  console.log(`Order ${i + 1}: Rs ${orders[i]}`);
}
Order 1: Rs 120
Order 2: Rs 80
Order 3: Rs 250

Rule: start at 0, use < length. If you don't need the index, for...of (episode 6) can't go wrong at all:

for (const amount of [120, 80, 250]) {
  console.log(amount);
}

Adding and removing: the queue at the stall

The queue Method What it does Returns
A new customer joins at the back push(x) add to the end the new length
The last person walks away pop() remove from the end the removed item
The front person is served shift() remove from the front the removed item
A VIP cuts in at the front unshift(x) add to the front the new length
const queue = ["Asha", "Ravi"];
queue.push("Meena");
console.log(queue);
const served = queue.shift();
console.log(`Served: ${served}`);
queue.unshift("VIP Kumar");
console.log(queue);
const left = queue.pop();
console.log(`${left} left the queue`);
console.log(queue, queue.length);
[ 'Asha', 'Ravi', 'Meena' ]
Served: Asha
[ 'VIP Kumar', 'Ravi', 'Meena' ]
Meena left the queue
[ 'VIP Kumar', 'Ravi' ] 2

length updates by itself. pop and shift hand back what they removed; on an empty array they return undefined. push can add several items at once: orders.push(120, 80, 250).

A const array can still change

const orders = [120, 80];
orders.push(250);
console.log(orders);
orders = [];
[ 120, 80, 250 ]
TypeError: Assignment to constant variable.

const locks the name (which array orders points to), not the contents. You can add coaches to the Rajdhani, but you can't stick the name "Rajdhani" on a different train. So: use const for arrays and change them with methods. To empty a const array, use orders.length = 0.

Searching: includes and indexOf

const menu = ["chai", "samosa", "vada pav"];
console.log(menu.includes("samosa"));
console.log(menu.indexOf("vada pav"));
console.log(menu.indexOf("pizza"));
console.log(menu.includes("Samosa"));
true
2
-1
false
  • includes(x) answers yes or no (true / false).
  • indexOf(x) gives the position of the first match, or -1 when it's not found.
  • Searching is exact, capital letters included: "Samosa" is not "samosa".

Always check for -1 before using an index from indexOf.

splice vs slice: scissors vs a photocopy

Ravi's order list Method Changes the original? Returns
Cut an order out with scissors splice(start, count, ...newItems) yes an array of the removed items
Photocopy part of the page slice(start, end) no a new array (end not included)
const orders = [120, 80, 250, 45, 600];
const removed = orders.splice(1, 1);
console.log(removed, orders);
orders.splice(2, 0, 99);
console.log(orders);
const firstTwo = orders.slice(0, 2);
console.log(firstTwo, orders);
[ 80 ] [ 120, 250, 45, 600 ]
[ 120, 250, 99, 45, 600 ]
[ 120, 250 ] [ 120, 250, 99, 45, 600 ]
  • splice(1, 1): from index 1, cut 1 item. The original lost 80.
  • splice(2, 0, 99): at index 2, cut nothing, insert 99.
  • slice(0, 2): indexes 0 and 1 (the end index 2 is not included); the original is untouched.

Memory trick: s-p-lice has a P for "permanent change"; slice is a photocopy.

The sort() trap: why 1000 comes before 80

const amounts = [120, 80, 1000, 250];
amounts.sort();
console.log(amounts);
[ 1000, 120, 250, 80 ]

By default, sort() turns every item into text and sorts in dictionary order. As text, "1000" starts with "1", which comes before "8", so it goes first. Great for words, wrong for numbers.

The fix: a compare rule

amounts.sort((a, b) => a - b);

(a, b) => a - b is a tiny function (episode 9 builds functions properly). sort hands it two items at a time:

a - b is... Meaning Order
negative a is smaller a first
positive b is smaller b first
zero equal keep as is

So a - b sorts small to big, b - a sorts big to small.

const amounts = [120, 80, 1000, 250];
amounts.sort((a, b) => a - b);
console.log(amounts);
amounts.sort((a, b) => b - a);
console.log(amounts);
console.log(["samosa", "chai", "vada pav"].sort());
[ 80, 120, 250, 1000 ]
[ 1000, 250, 120, 80 ]
[ 'chai', 'samosa', 'vada pav' ]

Numbers need a compare rule; words don't. Note that sort changes the original array (and returns that same array). To keep the original order, sort a copy: orders.slice().sort(...).

Copying vs sharing: two labels on one box

const today = [120, 80, 250];
const backup = today;
backup.push(999);
console.log(today);
const copy = today.slice();
copy.push(5);
console.log(today, copy);
console.log(today === backup, today === copy);
[ 120, 80, 250, 999 ]
[ 120, 80, 250, 999 ] [ 120, 80, 250, 999, 5 ]
true false

An array lives in one place in memory. backup = today doesn't copy it: it puts a second label on the same box (a reference). Changing backup changes today. slice() with no arguments makes a real copy (a second box). And === on arrays asks "is it the same box?", not "does it look the same?".

Handy methods

const items = ["chai", "samosa", "chai"];
console.log(items.join(", "));
console.log(items.join(" + "));
console.log(items.slice().reverse());
console.log(items.at(-1));
console.log("10,20,30".split(","));
console.log(typeof items, Array.isArray(items));
chai, samosa, chai
chai + samosa + chai
[ 'chai', 'samosa', 'chai' ]
chai
[ '10', '20', '30' ]
object true
Method What it does
join(sep) one string from all items, with sep between them
reverse() flips the order (changes the original, so reverse a copy)
at(-1) negative index counts from the end: the last item
split(sep) a string method (episode 4): text → array
Array.isArray(x) the reliable way to check for an array (typeof [] is "object")

Common mistakes (and what really happens)

You wrote What happens Why Fix
orders[3] on a 3-item array (no error) undefined indexes go 0 to length - 1 orders[orders.length - 1] for the last
for (let i = 0; i <= a.length; i++) (no error) an extra undefined off-by-one i < a.length, or for...of
orders = []; when orders is const TypeError: Assignment to constant variable. const locks the name orders.length = 0, or use let
[120, 80, 1000].sort() (no error) [ 1000, 120, 80 ] sorts as text sort((a, b) => a - b)
const backup = today; (no error) both change same array, two names today.slice()
order + i to build order1 ReferenceError: order is not defined names can't be built at run time an array: orders[i]
menu.splice(menu.indexOf("pizza"), 1) (no error) removes the last item indexOf gave -1, and -1 counts from the end check !== -1 first

Mini project: Ravi's order book

const orders = [];
orders.push(120, 80, 250, 45, 600);
const cancel = orders.indexOf(45);
if (cancel !== -1) {
  orders.splice(cancel, 1);
}
const top = orders.slice().sort((a, b) => b - a);
let total = 0;
for (const amount of orders) {
  total += amount;
}
console.log(`Orders: ${orders.join(", ")}`);
console.log(`Top 3: ${top.slice(0, 3).join(", ")}`);
console.log(`Total: Rs ${total} from ${orders.length} orders`);
console.log(`Any Rs 600 order? ${orders.includes(600)}`);
Orders: 120, 80, 250, 600
Top 3: 600, 250, 120
Total: Rs 1050 from 4 orders
Any Rs 600 order? true
  • push adds all five orders at once.
  • indexOf finds the cancelled order; the !== -1 check makes sure it was found before splice cuts it.
  • slice().sort(...) sorts a copy, so orders keeps its real order.
  • A running total with for...of, then join, slice(0, 3), length and includes for the report.

Try adding your own orders, or cancelling a different one.

Practice

  1. Store 5 marks in an array; print the highest and the lowest using sort.
  2. Remove "samosa" from ["chai", "samosa", "vada pav"] with indexOf + splice.
  3. Reverse [1, 2, 3, 4] without reverse() (use a loop).
  4. Count how many times "chai" appears in a list of orders.
Solutions and hints
  1. Sort a copy small to big; the first is the lowest, the last is the highest:
const marks = [72, 95, 48, 88, 61];
const sorted = marks.slice().sort((a, b) => a - b);
console.log(`Lowest: ${sorted[0]}`);
console.log(`Highest: ${sorted[sorted.length - 1]}`);
Lowest: 48
Highest: 95
  1. Find it, check it was found, cut it:
const menu = ["chai", "samosa", "vada pav"];
const i = menu.indexOf("samosa");
if (i !== -1) {
  menu.splice(i, 1);
}
console.log(menu);
[ 'chai', 'vada pav' ]
  1. Walk backwards from the last index and push into a new array:
const nums = [1, 2, 3, 4];
const reversed = [];
for (let i = nums.length - 1; i >= 0; i--) {
  reversed.push(nums[i]);
}
console.log(reversed);
[ 4, 3, 2, 1 ]
  1. A counter and for...of:
const orders = ["chai", "samosa", "chai", "vada pav", "chai"];
let count = 0;
for (const item of orders) {
  if (item === "chai") {
    count++;
  }
}
console.log(`chai: ${count}`);
chai: 3

Quick quiz

What does this print?

const a = [5, 1, 10];
a.sort();
console.log(a);
  • A. [ 1, 5, 10 ]
  • B. [ 1, 10, 5 ]
  • C. [ 10, 5, 1 ]
  • D. TypeError
Answer

B. With no compare function, sort compares the items as text: "1" < "10" < "5". Use a.sort((x, y) => x - y) to get [ 1, 5, 10 ].

Interview questions

  • Why do array indexes start at 0? How do you get the last element?
  • What happens when you read an index past the end of an array in JavaScript?
  • What's the difference between push/pop and unshift/shift? Which end does each work on?
  • Why can you push into a const array but not reassign it?
  • What's the difference between splice and slice?
  • Why does [10, 9, 1].sort() give [ 1, 10, 9 ]? How do you sort numbers correctly?
  • Does sort change the original array? How do you sort without changing it?
  • What does const b = a do for arrays? How do you copy an array?
  • Why is typeof [] equal to "object"? How do you check whether something is an array?
  • What does indexOf return when the item is missing, and why is that dangerous with splice?

Glossary

Term Meaning Example
Array an ordered list of values under one name [120, 80, 250]
Element (item) one value inside an array 80
Index the position of an element, starting at 0 orders[0] is the first
length the number of elements [1, 2, 3].length is 3
undefined "no value here": what you get past the end orders[3]
Off-by-one error going one step too far or too short i <= orders.length
Method a function that belongs to a value, called with a dot orders.push(5)
push / pop add / remove at the end queue.push("Meena")
unshift / shift add / remove at the front queue.shift()
includes does the array contain this value? menu.includes("chai") → true
indexOf position of a value, or -1 if not found menu.indexOf("pizza") → -1
splice cut (and insert) items, changing the array orders.splice(1, 1)
slice copy part of an array (end not included) orders.slice(0, 2)
sort sort the array in place (as text by default) a.sort((x, y) => x - y)
Compare function the rule sort uses to order two items (a, b) => a - b
Function (preview) a reusable piece of code; arrow form (a, b) => ... episode 9
Reference a label pointing at an array in memory backup = today shares it
Copy a separate second array with the same items today.slice()
join array → one string with a separator ["a", "b"].join("-") → "a-b"
reverse flips the order in place [1, 2].reverse() → [2, 1]
at read by index; negative counts from the end items.at(-1)
Array.isArray reliable check for an array Array.isArray([]) → true
const a name that can't be pointed at a new value const orders = []

Summary

  • An array is one name for a whole list: [120, 80, 250]. Indexes start at 0; the last item is at length - 1; past the end is undefined, with no error.
  • Loop with i < a.length (not <=), or for...of.
  • push/pop work at the end, unshift/shift at the front; pop and shift return what they removed.
  • A const array can still change its items; it just can't be replaced.
  • includes answers yes/no; indexOf gives the position or -1.
  • splice cuts the original; slice copies (end not included).
  • sort() sorts as text: for numbers use sort((a, b) => a - b), and sort a copy to keep the original.
  • = shares an array; slice() copies it. === asks "same array?".

Next episode: objects. Ravi wants each customer's name, phone and visits kept together; three separate arrays fall out of step, so you'll invent objects.