In this how-to guide we will discuss four different methods which can be used to add elements into JavaScript arrays. Here’s a list of the four methods we will discuss in this article:
- unshift()
- push()
- concat()
- splice()
Note: I will use the console to demonstrate the examples present in this post.
How to insert items to the start/beginning of an Array Using the unshift method
The unshift function is commonly used to add/insert elements to the start/beginning of an array. It is quite simple to use the unshift() method, just pass the element value you want to add to an array to the unshift() method and when the unshift() function is invoked, the element will be added to the array, and the index of the array will be automatically shifted down:
num.unshift(0);
console.log(num);
You can also add multiple values to an array using the unshift() method:
num.unshift(-5, -4, -3, -2, -1, 0);
console.log(num);
How to Add Elements to the End of an Array Using the push method
The push() method is used to insert items/elements to the last index of an Array. It takes one or more arguments (separated by commas) and adds them to the end of the specified array:
num.push(6);
console.log(num);
For multiple values:
num.push(6, 7, 8, 9);
console.log(num);
How to add Elements to an Array Using the concat() method
The concat() method does not actually add elements to the existing array but rather creates a new modified array. This method is helpful when we need the first array in its original state.
The concat() method can be used to add elements to both the beginning and end of the array:
var num2 =[].concat(-5, -4, -3, -2, -1, 0, num);
console.log(num2);
To add elements to the end of the array:
var num2 =[].concat(num, 6, 7, 8, 9);
console.log(num2);
How to add Elements to the middle of an Array using the splice() method
splice() is used to get rid of or insert elements in an array. This method is a bit different from the other methods which are discussed above. It requires three different arguments. The first argument defines where the item is going to be added in the array. The second parameter specifies the number of elements/items that are to be removed from the array. The second parameter will be zero in case of adding elements. The third parameter contains the values of the elements/items that are to be added.
num.splice(2, 0, 2.5);
console.log(num);
Conclusion
In this how-to guide we looked at four different ways of adding elements to an array in JavaScript. We can use the unshift() and the push() methods to add elements/items to the start and end of an array respectively. If we do not want to modify our original array but rather make a new array and add elements to it then we should use the concat() method. However, the splice() method gives us the most control over the index at which we want to add our new elements.