Tutorials / JavaScript Fundamentals / Arrays: creating, reading and changing lists

Arrays: creating, reading and changing lists

13 min read javascript
Course contents (16 lessons)
  1. Getting started
  2. What is JavaScript and where does it run?
  3. Variables with let and const
  4. Values and operators
  5. Data types: numbers, strings, booleans, null and undefined
  6. Operators: arithmetic, comparison and logical
  7. Strings and template literals
  8. Making decisions and repeating work
  9. Conditionals: if, else and switch
  10. Loops: for, while and for...of
  11. Functions
  12. Functions: declarations, parameters and return values
  13. Arrow functions and callbacks
  14. Arrays and objects
  15. Arrays: creating, reading and changing lists
  16. Array methods: map, filter, find and reduce
  17. Objects: properties, methods and copying
  18. Scope and the browser
  19. Scope and closures, gently
  20. The DOM: selecting and changing elements
  21. Events: reacting to clicks, input and forms
  22. Final project
  23. Project: build a to-do list in the browser

What an array is

An array is an ordered list of values. You use it whenever you have many things of the same kind: a list of products, usernames, prices or tasks. You write an array with square brackets and commas.

const fruits = ["mango", "apple", "banana"];
const mixed = [1, "two", true, null];
const empty = [];

An array can hold any type, even other arrays. In practice, keep one kind of thing in one array. It makes the code easier to work with.

Reading and changing items

Each item has a position, called an index, starting at 0.

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

console.log(fruits[0]);          // "mango"
console.log(fruits[2]);          // "banana"
console.log(fruits[5]);          // undefined, there is no item 5
console.log(fruits.length);      // 3
console.log(fruits.at(-1));      // "banana", last item

fruits[1] = "orange";            // replace an item
console.log(fruits);             // ["mango", "orange", "banana"]

The last item is always at length - 1. Reading a position that does not exist does not crash, it just gives undefined.

Remember the lesson on const. You can still change items of a const array. You only cannot assign a whole new array to the same name.

Adding and removing items

MethodWhat it doesReturns
push(x)Adds to the endNew length
pop()Removes from the endThe removed item
unshift(x)Adds to the startNew length
shift()Removes from the startThe removed item
splice(i, n, ...items)Removes n items at i, optionally inserts new onesArray of removed items
const queue = ["Ali", "Sara"];

queue.push("Omar");        // ["Ali", "Sara", "Omar"]
queue.unshift("Zain");     // ["Zain", "Ali", "Sara", "Omar"]
const last = queue.pop();  // "Omar"
const first = queue.shift(); // "Zain"
console.log(queue, last, first); // ["Ali", "Sara"] "Omar" "Zain"

const letters = ["a", "b", "c", "d"];
letters.splice(1, 2);          // remove "b" and "c"
console.log(letters);          // ["a", "d"]
letters.splice(1, 0, "x", "y"); // insert at position 1, remove nothing
console.log(letters);          // ["a", "x", "y", "d"]

These methods change the original array. That is called mutation. It is fine when you mean it, and a source of bugs when you do not. If you pass an array to a function and that function calls push, the caller's array changes too.

Finding things

const numbers = [10, 20, 30, 20];

console.log(numbers.includes(30));      // true
console.log(numbers.indexOf(20));       // 1
console.log(numbers.lastIndexOf(20));   // 3
console.log(numbers.indexOf(99));       // -1, not found

Slicing, joining and copying

slice takes a part of an array without changing the original. It works like the string version: the end position is not included.

const days = ["Mon", "Tue", "Wed", "Thu", "Fri"];
console.log(days.slice(1, 3));   // ["Tue", "Wed"]
console.log(days.slice(-2));     // ["Thu", "Fri"]
console.log(days.join(" | "));   // "Mon | Tue | Wed | Thu | Fri"

To make a copy, use the spread syntax [...array]:

const original = [1, 2, 3];
const copy = [...original];
const extended = [...original, 4, 5];

copy.push(99);
console.log(original); // [1, 2, 3], untouched
console.log(copy);     // [1, 2, 3, 99]
console.log(extended); // [1, 2, 3, 4, 5]

Just writing const copy = original does not make a copy. It gives the same array a second name. Changes through one name show up through the other. This is the single most common array bug I see in beginner code.

Sorting and reversing

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

By default sort turns items into strings and compares them as text, so "100" comes before "9". For numbers, pass a compare function:

nums.sort((a, b) => a - b);
console.log(nums); // [1, 9, 10, 100]

If a - b is negative, a goes first. sort and reverse also mutate the array. To keep the original, copy first: [...nums].sort((a, b) => a - b).

Arrays of arrays

Arrays can contain arrays, which is a simple way to model a grid:

const grid = [
  [1, 2, 3],
  [4, 5, 6],
];
console.log(grid[1][2]); // 6, second row, third column

Common mistakes

  • **Thinking const copy = original copies.** Use [...original].
  • Sorting numbers without a compare function. You get text order.
  • Off-by-one errors. The last index is length - 1.
  • Forgetting that push/pop/splice/sort mutate. Copy first if you need the original.
  • **Using delete array[1].** It leaves an empty hole. Use splice.

Try it yourself

  1. Create an array of five cities. Add one to the end, remove the first, and print the result.
  2. Given [5, 3, 8, 1], print the numbers sorted from smallest to largest without changing the original array.
  3. Make a copy of ["a", "b", "c"], add "d" to the copy, and show that the original did not change.
  4. Remove the item at position 2 from [1, 2, 3, 4, 5] using splice.
javascript
const fruits = ["mango", "apple", "banana"];

console.log(fruits[0]);          // "mango"
console.log(fruits[2]);          // "banana"
console.log(fruits[5]);          // undefined, there is no item 5
console.log(fruits.length);      // 3
console.log(fruits.at(-1));      // "banana", last item

fruits[1] = "orange";            // replace an item
console.log(fruits);             // ["mango", "orange", "banana"]

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account