Array Method: How to add and remove elements from Array

Array Method: How to add and remove elements from Array

Arrays can be defined with a length of any number of elements, and elements can be added or removed over time; in other words, arrays are mutable.

Add Items to an Array with push() and unshift()

Both methods take one or more elements as parameters and add those elements to the array the method is being called on; the push() method adds elements to the end of an array, and unshift() adds elements to the beginning.

let intOne = 1;
let arrayOfNumbers = [2, 3, 4];

arrayOfNumbers.push(5, 6); // [2, 3, 4, 5, 6]

arrayOfNumbers.unshift(intOne); // [1, 2, 3, 4, 5, 6]

In the above example we have defined a variable intOne which have the value 1 and arrayOfNumbers which is an array that have values [2, 3, 4]. Then we use Array.push() method on arrayOfNumbers and give two parameters as 5, 6. This method push or adds the given parameters to the end of the array. Hence arrayOfNumbers wil have values as [2, 3, 4, 5, 6].

Now we use the Array.unshift() method on arrayOfNumbers and pass a variable intOne. This method adds 1 to the beginning of arrayOfNumbers as [1, 2, 3, 4, 5, 6].

Remove Items from an Array with pop() and shift()

push() and unshift() are functional opposites of pop() and shift(). pop() removes an element from the end of an array, while shift() removes an element from the beginning. The key difference between pop() and shift() and their cousins push() and unshift(), is that neither method takes parameters, and each only allows an array to be modified by a single element at a time.

let arrayOfNumbers = [1, 2, 3, 4];

arrayOfNumbers.pop(); // 4

arrayOfNumbers.shift(); // 1

We have arrayOfNumbers and use pop() method on it. It will remove the last element from arrayOfNumbers and return 4. arrayOfNumbers will have the values [1, 2, 3].

Now we use shift() method which will remove first element from arrayOfNumbers and will return 1. arrayOfNumbers will have the values [2, 3].

Conclusion

Hence we saw how we can use push() and unshift() to add elements to an array and pop() and shift() to remove an element from array.