Execute Program

JavaScript Arrays: Stack

Welcome to the Stack lesson!

JavaScript arrays have `.push` and `.pop` methods. We can use those to build stack-like data structures, or to add and remove array elements.

This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!

  • We can add elements to the end of an array with .push(element).

  • >
    const numbers = [1, 2];
    numbers.push(3);
    numbers;
    Result:
    [1, 2, 3]Pass Icon
  • .push returns the array's length, including the newly-added element.

  • >
    const strings = ['a', 'b'];
    strings.push('c');
    Result:
  • >
    const strings = ['a', 'b', 'c', 'd'];
    strings.push('e');
    Result:
    5Pass Icon
  • Unlike some other array methods, .push doesn't return the array. It changes ("mutates") the array each time it's called.

  • >
    const numbers = [1];
    numbers.push(2);
    numbers;
    Result:
    [1, 2]Pass Icon
  • .pop is the opposite of push. It removes the last element from the array.

  • >
    const numbers = [1, 2, 3];
    numbers.pop();
    numbers;
    Result:
    [1, 2]Pass Icon
  • .pop returns the element that was removed.

  • >
    const numbers = [1, 2, 3];
    numbers.pop();
    Result:
    3Pass Icon
  • If the array is empty, .pop returns undefined, because there's nothing to remove. This mirrors the way that array indexing works: if we ask for any index of an empty array, we get undefined.

  • >
    const arr = [];
    arr[0];
    Result:
    undefinedPass Icon
  • >
    const arr = [];
    arr.pop();
    Result:
    undefinedPass Icon
  • Like .push, .pop also mutates the array.

  • >
    const numbers = [1, 2, 3];
    numbers.pop();
    numbers.pop();
    numbers;
    Result:
    [1]Pass Icon
  • >
    const a = [1, 2, 3];
    a.pop();
    a.push('a');
    a;
    Result:
    [1, 2, 'a']Pass Icon