How To Add New Elements To A JavaScript Array
There are several methods for adding new elements to a JavaScript array. Let's define them.
push()
The push() method is an in-built JavaScript method that is used to add a number, string, object, array, or any value to the Array. You can use the push() function that adds new items to the end of an array and returns the new length.
unshift()
Another method is used for appending an element to the beginning of an array is the unshift() function, which adds and returns the new length. It accepts multiple arguments, attaches the indexes of existing elements, and finally returns the new length of an array.
concat()
You also can use the concat() function, which merges two or more arrays. The concat method is one of the methods that is used to add elements to an array.
splice()
To insert elements in the middle of an array you can use the splice() method which can be used for appending or removing elements from an array.
In the example above, the first parameter (2) defines the position where new elements should be added (spliced in). The second parameter (0) defines how many elements should be removed. The other parameters ("Black", "Yellow") define the new elements to be added.
When you use the splice() method to add elements to an array, the second argument would be zero. The third and subsequent arguments are elements that should be added to the Array.