An Idea (by Ingenious Piece)

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

Follow publication

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.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

An Idea (by Ingenious Piece)
An Idea (by Ingenious Piece)

Published in An Idea (by Ingenious Piece)

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

Responses (1)

Write a response