Tutorials › JavaScript Tutorial › JavaScript Arrays

JavaScript Arrays

12 min read · Lesson 13 of 23

An array stores an ordered list of values in a single variable. Instead of creating product1, product2, product3…, you keep them all in one array and work with them together – count them, loop through them, sort them or search them.

Creating an array

Write the values inside square brackets, separated by commas.

Example JAVASCRIPT
const counties = ["Nairobi", "Mombasa", "Kisumu", "Nakuru"];
const prices = [50, 120, 75];
const mixed = ["Juma", 27, true];
const empty = [];

console.log(counties.length);
console.log(empty.length);
Result
4
0
Try it Yourself »

An array can hold any type of value, even a mix, but in practice each array usually holds one kind of thing.

Reading items by index

Each item has a numbered position called an index. Indexes start at 0.

Example JAVASCRIPT
const counties = ["Nairobi", "Mombasa", "Kisumu", "Nakuru"];

console.log(counties[0]);
console.log(counties[2]);
console.log(counties[counties.length - 1]);
console.log(counties.at(-1));
console.log(counties[10]);
Result
Nairobi
Kisumu
Nakuru
Nakuru
undefined
Try it Yourself »

Asking for an index that does not exist gives undefined, not an error.

Changing items

You can replace an item by assigning to its index.

Example JAVASCRIPT
const menu = ["chapati", "ugali", "githeri"];
menu[1] = "pilau";
console.log(menu.join(", "));
Result
chapati, pilau, githeri
Try it Yourself »

join(", ") turns the array into one string with the given separator between items – a handy way to print an array neatly.

Note: Arrays declared with const can still have their contents changed. const only stops you from assigning a whole new array to the variable.

Adding and removing items

MethodWhat it does
push(item)Adds to the end
pop()Removes and returns the last item
unshift(item)Adds to the start
shift()Removes and returns the first item
Example JAVASCRIPT
const queue = ["Ali", "Beth"];

queue.push("Chris");
queue.unshift("Dida");
console.log(queue.join(" -> "));

const served = queue.shift();
const last = queue.pop();
console.log(served, last);
console.log(queue.join(" -> "));
Result
Dida -> Ali -> Beth -> Chris
Dida Chris
Ali -> Beth
Try it Yourself »

Finding items

Example JAVASCRIPT
const fruits = ["mango", "banana", "pawpaw", "banana"];

console.log(fruits.includes("pawpaw"));
console.log(fruits.indexOf("banana"));
console.log(fruits.lastIndexOf("banana"));
console.log(fruits.indexOf("apple"));
Result
true
1
3
-1
Try it Yourself »

slice and splice

These two names look alike but behave differently.

  • slice(start, end) copies part of the array into a new array. The original is untouched.
  • splice(start, deleteCount, ...newItems) changes the original: it removes and/or inserts items.
Example JAVASCRIPT
const days = ["Mon", "Tue", "Wed", "Thu", "Fri"];

const midweek = days.slice(1, 4);
console.log(midweek.join(","));
console.log(days.length);

days.splice(2, 1, "HOLIDAY");
console.log(days.join(","));
Result
Tue,Wed,Thu
5
Mon,Tue,HOLIDAY,Thu,Fri
Try it Yourself »

Combining arrays and the spread operator

concat() joins arrays. The spread operator ... does the same job and is more flexible: it "spreads" the items of an array into a new one.

Example JAVASCRIPT
const east = ["Kenya", "Uganda", "Tanzania"];
const more = ["Rwanda", "Burundi"];

const eac = [...east, ...more, "South Sudan"];
console.log(eac.length);
console.log(eac.join(", "));

const copy = [...east];
copy.push("DRC");
console.log(east.length, copy.length);
Result
6
Kenya, Uganda, Tanzania, Rwanda, Burundi, South Sudan
3 4
Try it Yourself »

Spreading into a new array is the easiest way to copy an array, so changes to the copy do not affect the original.

Destructuring

Destructuring unpacks array items into separate variables in one line.

Example JAVASCRIPT
const podium = ["Kipchoge", "Kiplagat", "Cheruiyot"];
const [gold, silver, bronze] = podium;
console.log(`Gold: ${gold}, Bronze: ${bronze}`);

const [first, ...others] = podium;
console.log(first, others.length);
Result
Gold: Kipchoge, Bronze: Cheruiyot
Kipchoge 2
Try it Yourself »

Arrays of arrays

An array can contain other arrays, which is useful for grids and tables.

Example JAVASCRIPT
const seating = [
  ["A1", "A2"],
  ["B1", "B2"],
];
console.log(seating[1][0]);
Result
B1
Try it Yourself »

Checking for an array

Because typeof [] is "object", use Array.isArray():

Example JAVASCRIPT
console.log(Array.isArray(["x"]));
console.log(Array.isArray("x"));
Result
true
false
Try it Yourself »
Tip: The real power of arrays comes from methods like map, filter and reduce. They are the subject of the next lesson, Array Methods.
Exercise

Add "Thika" to the end of the towns array.

towns.("Thika");
Exercise

Get the first item of the array.

const firstTown = towns[];
Sign in or create a free account to track progress, earn XP, badges and a certificate.