CodeBlanks Logo Icon CodeBlanks

Adding elements to arrays

JavaScript course · Beginner · Lesson 43/133

Learn to add elements to the end and start of an array with push and unshift.

Appending with push

The most common way to add an element to an array is the push method. push adds the element to the end of the array and returns the new length.

Example: fruits.push("banana"); modifies the array directly (mutates it). The new element lands at the last index.

You can add multiple elements too: fruits.push("banana", "cherry"); adds both in order.

Prepending with unshift

The unshift method adds an element to the start of the array. The new element lands at index 0; the others shift by one.

Example: when fruits = ["banana", "cherry"], calling fruits.unshift("apple"); turns it into ["apple", "banana", "cherry"].

Like push, unshift returns the new length and modifies the array directly. Multiple elements can be added; they are all prepended in order.

Exercise Add elements to the list array

Create an empty array named list. First add a string with push, then add another string with unshift.

Show example solution
Start with const list = [], then add a string each with push and unshift.
Example solution:
const list = [];
list.push("last");
list.unshift("first");

Test yourself

  1. Add a new task to the tasks array

    const tasks = ["homework", "sport"];
    tasks.push(____);
    console.log(tasks);
    Show answer
    const tasks = ["homework", "sport"];
    tasks.push("shopping");
    console.log(tasks);
  2. After the code runs, at which index does 'mark' land in the array?

    const queue = ["alex", "anna"];
    queue.push("mark");
    • 0
    • 1
    • 2
    • 3
    Show answer

    2 — Correct. push appends to the end; 'mark' lands at index 2.

  3. Match each method with its behavior

    push
    appends an element to the end
    unshift
    prepends an element to the start
    length
    returns the element count

All lessons in Beginner