Skip to content
Kuza Ndoto Academy

Arrays

Beginner → IntermediateChapter 3 · Page 15 of 324 min readUpdated 15 Nov 2026

An array is an ordered list of values stored under one name: the stops on a matatu route, the marks in a class or the items in a shopping cart. Arrays can grow and shrink, hold any type of value, and come with many built-in methods.

Creating arrays and reading items

Write an array as values in square brackets, separated by commas. Each item has a numbered position called an index, starting at 0.

const matatuStops = ["Kencom", "Odeon", "Ngara", "Pangani"];

console.log(matatuStops[0]);
console.log(matatuStops[2]);
console.log(matatuStops.length);
console.log(matatuStops[matatuStops.length - 1]);
console.log(matatuStops.at(-1));
Kencom Ngara 4 Pangani Pangani
matatuStops index 0 1 2 3 "Kencom" "Odeon" "Ngara" "Pangani" at() -4 -3 -2 -1 length = 4 (last index = 3)
Figure 1. Indexes start at 0, so the last item is always at length - 1. at() also accepts negative indexes that count back from the end.

Reading an index that doesn't exist, like matatuStops[10], gives undefined. Arrays can hold mixed types, even other arrays, but in practice you usually keep one kind of value per array. typeof reports arrays as "object", so test with Array.isArray(value).

Tip

Array or object? Use an array when the order matters and every item is the same kind of thing: a list of stops, a queue of customers, a set of marks. Use an object when you describe one thing with named details, such as a student's name, age and county. Real data often combines both: an array of student objects is the shape you will meet most in apps and APIs.

Common mistake

Because indexes start at 0, the condition in a counting loop must be i < arr.length, not i <= arr.length. With <= the loop runs one extra time and reads arr[arr.length], which is undefined. This off-by-one error is one of the most common bugs in any language.

Adding and removing items

Four methods change the ends of an array:

const queue = ["Ali", "Beth"];

queue.push("Chris");        // add to the end
console.log(queue);
queue.unshift("Zara");      // add to the start
console.log(queue);

const served = queue.shift();   // remove from the start
console.log(served, queue);
const last = queue.pop();       // remove from the end
console.log(last, queue);
['Ali', 'Beth', 'Chris'] ['Zara', 'Ali', 'Beth', 'Chris'] Zara ['Ali', 'Beth', 'Chris'] Chris ['Ali', 'Beth']

shift and pop return the item they removed; push and unshift return the new length. You can also replace an item directly: queue[0] = "Daudi";. To remove or insert in the middle, use splice(start, deleteCount, ...newItems):

const days = ["Mon", "Tue", "Wed", "Thu"];

days.splice(1, 2);              // from index 1, remove 2 items
console.log(days);
days.splice(1, 0, "Fri", "Sat"); // at index 1, remove 0, insert 2
console.log(days);
['Mon', 'Thu'] ['Mon', 'Fri', 'Sat', 'Thu']
Common mistake

Don't confuse splice with slice. splice changes the original array. slice(start, end) returns a new array with a copy of part of it and leaves the original alone: [10, 20, 30, 40].slice(1, 3) gives [20, 30].

Searching and joining

const fruits = ["mango", "banana", "avocado"];

console.log(fruits.includes("banana"));
console.log(fruits.indexOf("avocado"));
console.log(fruits.indexOf("apple"));
console.log(fruits.join(", "));
true 2 -1 mango, banana, avocado

indexOf returns -1 when the item isn't found. join glues every item into one string with the separator you choose; its opposite is the string method split. For searching by a condition (for example, the first student with a score above 90), use find on the Array Methods page.

Copying, spreading and destructuring

Arrays are objects, so assigning one to another variable copies only the reference (see Data Types). Use the spread syntax ... to make a real copy or to combine arrays:

const a = [1, 2, 3];
const b = a;          // same array, second name
const c = [...a];     // new array with the same items
b.push(4);

console.log(a);
console.log(c);
console.log([...c, ...[7, 8]]);
[1, 2, 3, 4] [1, 2, 3] [1, 2, 3, 7, 8]

Array destructuring unpacks items by position, and a rest element gathers the remainder:

const [first, second, ...others] = ["gold", "silver", "bronze", "fourth"];
console.log(first, second, others);

let x = 1;
let y = 2;
[x, y] = [y, x];     // swap
console.log(x, y);
gold silver ['bronze', 'fourth'] 2 1

Looping and nested arrays

Use for...of to visit each value, or a counting for loop when you need the index (see Loops). Arrays can contain arrays, which is handy for grids and tables: in const grid = [[1, 2, 3], [4, 5, 6]];, grid[1][0] is 4 (row 1, column 0).

const prices = [120, 80, 250];
prices.push(50);

let total = 0;
for (const p of prices) {
  total += p;
}

console.log("Items:", prices.length);
console.log("List:", prices.join(" + "));
console.log("Total: KES", total);
Items: 4 List: 120 + 80 + 250 + 50 Total: KES 500

Key points

  • Arrays are ordered lists; indexes start at 0 and the last item is at length - 1 (or at(-1)).
  • push/pop work on the end, unshift/shift on the start, splice anywhere.
  • includes, indexOf and join search and combine; slice copies part without changing the array.
  • Assigning an array shares it; [...arr] makes a copy.
  • Destructuring unpacks items by position.
Up next · Functions, Objects & ArraysArray MethodsforEach, map, filter, reduce, find and sort.
→

Tip: use the ← and → keys to move between pages.