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]
.pushreturns 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:
5
Unlike some other array methods,
.pushdoesn't return the array. It changes ("mutates") the array each time it's called.>
const numbers = [1];numbers.push(2);numbers;Result:
[1, 2]
.popis the opposite of push. It removes the last element from the array.>
const numbers = [1, 2, 3];numbers.pop();numbers;Result:
[1, 2]
.popreturns the element that was removed.>
const numbers = [1, 2, 3];numbers.pop();Result:
3
If the array is empty,
.popreturnsundefined, 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 getundefined.>
const arr = [];arr[0];Result:
undefined
>
const arr = [];arr.pop();Result:
undefined
Like
.push,.popalso mutates the array.>
const numbers = [1, 2, 3];numbers.pop();numbers.pop();numbers;Result:
[1]
>
const a = [1, 2, 3];a.pop();a.push('a');a;Result:
[1, 2, 'a']