DEV Community

Cover image for JavaScript array push, pop, shift, unshift: how to remember the difference
Yaphi Berhanu
Yaphi Berhanu

Posted on • Originally published at simplestepscode.com

JavaScript array push, pop, shift, unshift: how to remember the difference

When you're adding and removing stuff from the beginning and end of a JavaScript array, it can be tough to remember which method does what. Here are some tips:

  • Unshift and shift make the whole array shift sideways (by adding and removing items from the beginning).

  • Push and pop do NOT make the array shift sideways (because they add and remove items at the end).

  • In each of those pairs (push/pop and unshift/shift), the longer word makes the array longer.

If you're curious, I made a quick animation to illustrate these points.

I hope this helps!


Note that this is more of a memorization trick than a full explanation, so feel free to check out MDN for full details and examples of push, pop, shift, and unshift.

Top comments (3)

Collapse
 
daveblythe profile image
Dave Blythe (he/him)

Bookmarked!!!
Being a rather visually-focused learner, your linked animation is probably the coolest thing I've seen this week! Great concept, very clear... and something I'm sure I'll retain!
Nicely done :)

Collapse
 
yaphi1 profile image
Yaphi Berhanu

Glad the animation was helpful!

Collapse
 
joepshoulak profile image
Joe P Shoulak

I created an account just to tell you how much I appreciate the simple and unforgettable method of remembering these functions. I've had to look it up 10 times in the last week, and now, never again!