Arrays

JavaScript · Lesson 21 of 61 7 min read Updated

A class has 40 students, a shopping cart has 6 items, a train has 22 coaches. Creating a separate variable for each one would be impossible to manage. An array stores a whole list of values in a single variable, in order, so you can count them, loop over them, search them and change them.

In this lesson you will create arrays, read and change their items, add and remove items, search them, and understand why copying an array needs care.

Creating an array and reading items

Write an array with square brackets, with the items separated by commas. Each item has a position called its index, and the first index is 0.

JavaScriptRun it yourself
const subjects = ["Maths", "Physics", "Chemistry", "English"];

console.log(subjects);
console.log(subjects.length);
console.log(subjects[0]);
console.log(subjects[3]);
console.log(subjects.at(-1));
console.log(subjects[10]);
Output
[ 'Maths', 'Physics', 'Chemistry', 'English' ]
4
Maths
English
English
undefined
  • length is the number of items. The last index is always length - 1.
  • subjects[0] reads the first item.
  • at(-1) reads the last item; negative numbers count from the end.
  • Reading an index that does not exist gives undefined, not an error.

An array can hold any kind of value, even a mix of numbers, strings and objects. In practice, keep one kind of thing per array, such as all prices or all students, so every item can be treated the same way.

To change an item, assign to its index: subjects[3] = "Computer Science";. This works even though subjects is a const, because const only stops you from pointing the name at a different array, as you learned in Variables: let and const.

Adding and removing items

Four methods add or remove items at the ends of an array. Think of the queue at a ration shop:

JavaScriptRun it yourself
const queue = ["Aarav", "Meera"];

queue.push("Kabir");          // joins at the end
console.log(queue);

const served = queue.shift(); // first person is served
console.log(served, queue);

queue.unshift("Dadi ji");     // an elderly person is let in first
console.log(queue);

const left = queue.pop();     // last person leaves
console.log(left, queue);
Output
[ 'Aarav', 'Meera', 'Kabir' ]
Aarav [ 'Meera', 'Kabir' ]
[ 'Dadi ji', 'Meera', 'Kabir' ]
Kabir [ 'Dadi ji', 'Meera' ]
MethodDoesReturns
push(x)Adds to the endThe new length
pop()Removes from the endThe removed item
unshift(x)Adds to the startThe new length
shift()Removes from the startThe removed item

All four mutate (change) the original array. push() and pop() are fast. shift() and unshift() must move every other item, so they are slower on very large arrays, though you will not notice with normal lists.

Removing from the middle: splice()

splice(start, deleteCount, ...newItems) removes and/or inserts items at any position, and returns the removed items as an array.

JavaScriptRun it yourself
const playlist = ["Kesariya", "Tum Hi Ho", "Chaiyya Chaiyya", "Jai Ho"];

const removed = playlist.splice(1, 2); // from index 1, remove 2 items
console.log(removed);
console.log(playlist);

playlist.splice(1, 0, "Malhari");      // at index 1, remove 0, insert one
console.log(playlist);
Output
[ 'Tum Hi Ho', 'Chaiyya Chaiyya' ]
[ 'Kesariya', 'Jai Ho' ]
[ 'Kesariya', 'Malhari', 'Jai Ho' ]

splice() changes the array in place. Modern JavaScript also has toSpliced(), which returns a changed copy and leaves the original alone; you will see it in Array Methods.

Searching and joining

JavaScriptRun it yourself
const cart = ["rice", "dal", "ghee"];

console.log(cart.includes("dal"));
console.log(cart.indexOf("ghee"));
console.log(cart.indexOf("sugar"));
console.log(cart.join(", "));
console.log("Items: " + cart.join(" + "));
console.log(Array.isArray(cart));
Output
true
2
-1
rice, dal, ghee
Items: rice + dal + ghee
true
  • includes(x) answers yes or no.
  • indexOf(x) gives the index of the first match, or -1 when it is not found.
  • join(separator) builds one string from all items. It is the opposite of the string method split() from Strings & Template Literals.
  • Array.isArray(x) checks whether a value is an array; typeof would only say "object".

To search with a condition, such as "the first order above ₹1,000", use find() and findIndex(), covered in Array Methods.

Copying arrays

An array is an object, so assigning it to another variable does not copy it. Both names point to the same array.

JavaScriptRun it yourself
const original = [10, 20, 30];
const sameArray = original;
const copy = original.slice();

sameArray.push(40);

console.log(original);
console.log(copy);
console.log(original === sameArray);
console.log(original === copy);
Output
[ 10, 20, 30, 40 ]
[ 10, 20, 30 ]
true
false

slice() with no arguments returns a new array with the same items. The spread syntax [...original] does the same and is very common; see Destructuring, Rest & Spread.

The last two lines show another trap: === on arrays checks whether both sides are the same array, not whether they contain the same items. [1, 2] === [1, 2] is false.

Arrays inside arrays

An array item can itself be an array. This gives you a grid, such as the seats in a cinema hall:

JavaScript
const seats = [
  ["A1", "A2", "A3"],
  ["B1", "B2", "B3"],
  ["C1", "C2", "C3"],
];

console.log(seats[1][2]);   // "B3": row index 1, seat index 2
console.log(seats.length);  // 3 rows

The first index picks the row, the second picks the item in that row.

Looping over arrays

To visit every item, use for...of, which you learned in for...of and for...in:

JavaScript
for (const subject of subjects) {
  console.log(subject);
}

Arrays also have powerful looping methods such as map(), filter() and reduce(), which are the topic of the next lesson.

Common mistakes

  • Counting from 1. The first item is list[0] and the last is list[list.length - 1] or list.at(-1).
  • Thinking = copies. const b = a shares one array. Use a.slice() or [...a].
  • Comparing arrays with ===. It compares identity, not contents.
  • Forgetting that push(), pop(), shift(), unshift() and splice() change the original. If other code uses the same array, it sees the change too.

Key points

  • An array is an ordered list in square brackets; indexes start at 0.
  • length gives the number of items; at(-1) gives the last one.
  • push/pop work at the end, unshift/shift at the start, splice anywhere; all change the array.
  • includes, indexOf and join search and combine items.
  • Assigning an array shares it; slice() or [...arr] makes a copy.
  • Arrays can contain arrays to form grids.

Exercise

Kabir's to-do list is ["Buy milk", "Pay rent", "Call Ananya"]. Add "Book train ticket" at the end, remove "Pay rent" (it is done) using indexOf() and splice(), add "Gym" at the very start, then print the list as one numbered string like "1. Gym | 2. Buy milk | ..." by looping with entries().

Show solution
JavaScript
const todos = ["Buy milk", "Pay rent", "Call Ananya"];

todos.push("Book train ticket");
todos.splice(todos.indexOf("Pay rent"), 1);
todos.unshift("Gym");

const parts = [];
for (const [i, task] of todos.entries()) {
  parts.push(`${i + 1}. ${task}`);
}
console.log(parts.join(" | "));
Output
1. Gym | 2. Buy milk | 3. Call Ananya | 4. Book train ticket

indexOf() finds where "Pay rent" is, so the code still works if the list order changes. The numbered pieces are collected in a new array and joined at the end.

Quick Quiz

1. For const a = ["x", "y", "z"], what is a.length - 1?

2. What does pop() return?

3. What is [1, 2] === [1, 2]?

4. Which line makes a real copy of list?

Learn JavaScript with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call