Adding and Removing Items from an Array. Javascript

Arrays essential part in most programming languages including javascript. Mastering it makes your programming life easier than you think. This article is for javascript beginners, and it provides essential array methods every programmer should know.

Unlike some other programming languages like java, c++, c,… in javascript array size is not fixed, meaning that you can add, remove, and change array size however you want.

Adding new item

push() method is used to add new items to the end of an array. You can pass items as an argument of this method.

unshift() method is used to add new items from the beginning of the array. Here also you should pass new items as an argument of the method.

Removing items

pop() method is used to remove the last item of an array.

shift() method is used to remove the first item of an array. After removal of the first item all items are shifted forward and their index change respectively.

Note: Keep in mind that these methods directly change the current array and they return different results.

Inserting or removing items in the middle

splice() method is used for both inserting and removing items in the middle of an array. This method takes 2 main arguments. This method removes a specified number of items starting from a specified index. The first argument is the index of an array where removal should start. The second argument is the number of items to be removed.

After the second argument, you can pass as many values as you want in order to insert them in the same place.

Other methods

This one is not a method and guess you are very familiar with it but thought it worth mentioning this. length every array has this property and it keeps track of the length of our array.

slice() method is used to take some part of an array. The index of starting point is passed as the first argument, and the ending index is passed for the second argument. The ending index will not be included in the extracted array. If there is no second argument it extracts items till the end of an array. Keep in mind that this method returns extracted array and won’t change the original array.

React dev.

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