Menu Home

Array.push(), pop(), unshift(), shift()

Hi everyone, and welcome to a gut-busting episode of Boring JavaScript! Today, we tackle four – yes, FOUR – methods on Arrays: push(), pop(), unshift(), and shift(). All four of the methods we’re talking about today deal with adding or removing elements from the beginning or the end of arrays.

Get bored reading? Then get put to sleep by watching our video.

When Push Comes to Shove

Our first method is the Array.push() method. Taking any number of arguments, JavaScript will add the arguments in order as entries onto the end of the array. Let’s look at an example:

const animals = [
	"Cat", "Dog", "Horse", "Cow", "Coyote", "Road Runner", "Dolphin", "Whale", "Lizard"
];

const dinosaur = "Dinosaur";
const bird = {
	name: "Tweety",
	type: "Bird",
	color: "yellow"
}

animals.push(dinosaur);
animals.push(bird);

console.log(animals);

/* output
[
  'Cat',
  'Dog',
  'Horse',
  'Cow',
  'Coyote',
  'Road Runner',
  'Dolphin',
  'Whale',
  'Lizard',
  'Dinosaur',
  { name: 'Tweety', type: 'Bird', color: 'yellow' }
]
*/

The first push (Line 12) added the word “Dinosaur” to the end of the array (Element index 9). The second push (Line 13) added an Object to the end of the array (Element index 10). The result is in the output above.

Notice that we pushed both a String and an Object. Since Arrays can have any type of entries, you can push anything you want onto the array.

Pop! Goes the Weasel

If Array.push() puts an element onto the end of the array, how do you get it back off? That’s with the Array.pop() method, which will remove the last element of the array and return that element back to the caller. Let’s take a look.

const animals = [
	"Cat", "Dog", "Horse", "Cow", "Coyote", "Road Runner", "Dolphin", "Whale", "Lizard"
];

const lostAnimal = animals.pop();

console.log(animals);
console.log(`Lost animal is: ${lostAnimal}`)

/* output
[
  'Cat',
  'Dog',
  'Horse',
  'Cow',
  'Coyote',
  'Road Runner',
  'Dolphin',
  'Whale'
]
Lost animal is: Lizard
*/

As you can see from the output, the ‘animals’ array lost the last element of the array (‘Lizard’) when the Array.pop() was executed (Line 5).

What happens if the array is empty? No change is made to the Array, and no error is thrown. The value returned from Array.pop() is undefined.

const animals = [];
const lostAnimal = animals.pop();
console.log(animals);
console.log(`Lost animal is: ${lostAnimal}`)

/* output
[]
Lost animal is: undefined
*/

The Unshift: Old Cola Commercial

Array.push() and Array.pop() works on the end of the array, but what about the beginning?

No problem! You can use the Array.unshift() method to add elements to the beginning of the array. Let’s look an example:

const animals = [
	"Cat", "Dog", "Horse", "Cow", "Coyote", "Road Runner", "Dolphin", "Whale", "Lizard"
];

const dinosaur = "Dinosaur";

animals.unshift(dinosaur);

console.log(animals);

/* output
[
  'Dinosaur',    'Cat',
  'Dog',         'Horse',
  'Cow',         'Coyote',
  'Road Runner', 'Dolphin',
  'Whale',       'Lizard'
]
*/

As opposed to Array.push(), Array.unshift() adds the element to the beginning of the array. Like Array.push(), Array.unshift() takes multiple argumenta, and prepends those arguments as elements to the beginning of the array (Line 7). In our example, ‘Dinosaur’ now appears at the beginning of the array.

Shifting Lanes

We can put an element on the beginning of the array – how about taking it off the beginning? That can be done with the Array.shift() method. Like Array.pop(), it takes no arguments, and returns the element that was removed from the array.

const animals = [
	"Cat", "Dog", "Horse", "Cow", "Coyote", "Road Runner", "Dolphin", "Whale", "Lizard"
];

const lostAnimal = animals.shift();

console.log(animals);
console.log(`Lost animal is: ${lostAnimal}`)

/* output
[
  'Dog',
  'Horse',
  'Cow',
  'Coyote',
  'Road Runner',
  'Dolphin',
  'Whale',
  'Lizard'
]
Lost animal is: Cat
*/

The Array.shift() in line 5 preforms the operation by taking the first element (‘Cat’) from the beginning of the array and returning that value. The array itself is changed.

What if there are no elements in the array? Just like Array.pop(), nothing happens to the array, no error is thrown, and the returned value is undefined.

const animals = [];
const lostAnimal = animals.shift();
console.log(animals);
console.log(`Lost animal is: ${lostAnimal}`)

/* output
[]
Lost animal is: undefined
*/

The video

As always, we have a video that explains all of the above. Check it out! And make sure to subscribe to our YouTube channel.

Shameless Plugs

Check out all our videos at Boring JavaScript.

Check out everything at TheVirtuoid.

Facebook

Twitter

YouTube

Categories: Boring JavaScript Javascript

Tagged as:

thevirtuoid

Web Tinkerer. No, not like Tinkerbell.

Creator of the game Virtuoid. Boring JavaScript. Visit us at thevirtuoid.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: