Common Array methods in JavaScript

Ashok Maharjan
3 min readJul 4, 2020

--

We have already seen how arrays are defined in Javascript in an earlier blog. Now, let’s look at some common array methods available to us.

https://www.positronx.io/wp-content/uploads/2018/10/positronx-jquery-002.jpg

Once we create an array, we can access each element of an array using the index of the element. We have to remember that we start the counting from ‘0’ not from ‘1’. We can also get the number of elements of an array using ‘.length’.

Array Manipulations:

To add and remove elements at the end of the array, we use push() and pop() methods.

To add and remove at the beginning of an array, we use unshift() and shift() methods.

However, it is important to remember the return values of these methods; pop() and shift() returns the element that was removed from the array, whereas push() and unshift() returns the new length of the array.

What if we want to add multiple elements? We can do that as well by using concat() method. Let’s take the above arrays for example, all pets are in fact animals, so we can combine them together. We can use concat() and pass just the elements as arguments or pass an array or elements.

Again, we can see that concat(), returns the new array with the elements added but it does not modify the original array.

Slice and Splice:

Slice() method is used to create the subarray from any array and it takes the starting index as an argument. We can also use a second argument to indicate where the slicing should stop but it is optional.

Splice() allows us to add/replace elements in the various indices of an array. The first argument is the index where splicing begins, second one is the number of elements to remove and remaining is the elements to add to the array. If we only provide the first and second argument, the subarray would be removed but nothing would be replaced. We can also use ‘0’ as a second argument if we want nothing to be removed.

These are just some common array methods, we can learn about all other array methods here. That’s all for today, we will explore some more JavaScript in the next blog. Happy Coding !!

--

--