JavaScript Arrays: push(), pop(), shift() & unshift()

When working with arrays, it is important to understand the different types of methods and how they transform your data. push(), pop(), shift() and unshift() are only four of many other such methods.

Photo by Faris Mohammed on Unsplash

push()

  • adds one or more elements to the end of an array
  • returns the new element(s)
  • is destructive, so the array itself will be mutated
  • relies on the length property to know where to insert the new element(s) and will default to 0 if there is no length
from MDN web docs

pop()

  • works the same way as push(), except that it removes the last element or elements from an array
  • returns the removed element(s) and will return undefined if they array is empty
  • is also a destructive method and will mutate the original array
  • relies on the length property as well
from MDN web docs

shift()

  • works from the beginning of the array and removes the first element
  • like pop(), it returns the removed element or undefined
  • is destructive
  • relies on length property
from MDN web docs

unshift()

  • is the opposite of shift() and inserts element(s) at the beginning of the array
  • returns the new element(s)
  • is destructive
  • relies on the length property
from MDN web docs

These four array methods are quite similar to each other in the way they work and the fact that they are all destructive. It also makes it easy to get their definitions mixed up. I personally have trouble remembering shift() and unshift() because the names are a bit too similar — thank goodness for Google!

If you are new here and liked the article, there are many more like this on Medium. You can sign up to read them for just $5 a month.

Here is the link for unlimited access to every content here on Medium. If you sign up by using this link, I’ll earn a small amount at no additional cost to you.

--

--

--

No Matter What People Tell You, Words And Ideas Can Change The World.

Recommended from Medium

RxJS: How to Observe an Object

Code Splitting for React Router with Webpack and HMR

Using TypeScript with Google Cloud Functions without compiling

How to : Quick resize squashfs image in openwrt 19.07.3 x86–64

React JS and its Advantages: A Quick Guide

How to start Learning Front-end Development from Scratch:

My Experience Contributing Towards Open Source Software

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Amanda M Johnson

Amanda M Johnson

Full Stack Software Engineer | manda.m.johnson@gmail.com

More from Medium

What TypeScript Really Means for Our JavaScript Code

Using JavaScript and window.postMessage() for Safe Cross-Domain Communication

TypeScript vs JavaScript: What’s the Difference?

5 Ways to Judge Array in TypeScript