push and pop
- Node.js course
- Beginner
- Lesson 55/116
- 5 min
Learn to add/remove at the end with .push and .pop.
Appending with push
To add an element at the end of an array you use .push(x). arr.push(5) places 5 at the end of arr and returns the new length. Several values can be added: arr.push(1, 2).
push modifies the array in place; it does not create a new one. For example after const nums = [1, 2]; nums.push(3);, nums becomes [1, 2, 3]. push is especially common when accumulating elements in a loop; each iteration appends a new element at the end.
Removing from the end with pop
To remove the last element of an array you use .pop(). It returns the removed element and the array length shrinks by one. In const nums = [1, 2, 3]; const last = nums.pop();, last becomes 3 and nums is left as [1, 2].
Calling pop on an empty array returns undefined; no error is thrown. push and pop together give LIFO (last in first out) stack behavior. They are handy when you want to remove the most recently added element of a list first. pop also modifies the array in place.
Practice Append with push and print
The nums variable is set to [1, 2]. Append 3 with nums.push(3); then print nums[2] with console.log. The output on a single line must be 3.
Starter code
const nums = [1, 2];
// Append 3 to nums; print the third elementSample solution
const nums = [1, 2];
nums.push(3);
console.log(nums[2]);Expected output
3
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each method to its job
| Term | Meaning |
|---|---|
push |
Appends at end |
pop |
Removes from end |
length |
Element count |
[0] |
First element |
2 Write the push call
const nums = [1, 2];
nums____(3);
const nums = [1, 2];
nums.push(3);
Explanation: .push appends to the array.
3 What is the result of const a = [1, 2, 3]; a.pop();?
const a = [1, 2, 3];
a.pop();- a = [1, 2, 3]
- a = [2, 3]
- a = [1, 2] Correct answer
- a = []
Explanation: pop removes the last element; a becomes [1, 2].