Array Methods - push, pop, unshift, shift
Let's learn about methods for managing elements within an array.
array.push
The push
method adds a new item to the end of an array. It's like adding a card to the top of a stack of cards.
Example:
const fruits = ['apple', 'banana']; fruits.push('cherry'); console.log(fruits); // Output: ["apple", "banana", "cherry"]
array.pop
The pop
method removes the last item from an array and returns that item. It's like taking the top card from a stack of cards.
Example:
const fruits = ['apple', 'banana', 'cherry']; const lastFruit = fruits.pop(); console.log(lastFruit); // Output: "cherry" console.log(fruits); // Output: ["apple", "banana"]
array.unshift
The unshift
method adds a new item to the beginning of an array. It's like adding a card to the bottom of a stack of cards.
Example:
const fruits = ['banana', 'cherry']; fruits.unshift('apple'); console.log(fruits); // Output: ["apple", "banana", "cherry"]
array.shift
The shift
method removes the first item from an array and returns that item. It's like taking the bottom card from a stack of cards.
Example:
const fruits = ['apple', 'banana', 'cherry']; const firstFruit = fruits.shift(); console.log(firstFruit); // Output: "apple" console.log(fruits); // Output: ["banana", "cherry"]
What does the array.pop
method do?
Returns the first item of the array.
Adds an item to the first position of the array.
Returns the last item of the array.
Adds an item to the last position of the array.
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result