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:
You can also add multiple values to an array using the unshift() method:
num.unshift(-5, -4, -3, -2, -1, 0);
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:
For multiple values:
num.push(6, 7, 8, 9);
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);
To add elements to the end of the array:
var num2 =.concat(num, 6, 7, 8, 9);
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);