Adding an element to an array is straight forward in many cases, that is by using ‘push’ method, which is available for arrays in JavaScript.
example:
Though the ‘push’ method is sufficient in most cases, the limitation with this method can be, the element will be added only at the end of the array.
Add an element at the beginning of an Array
This is also straight forward, we can use the ‘unshift’ method of JavaScript to add an element at the beginning of any array.
example:
How to add an element to an array at the end, without using ‘push’ method in JavaScript
For some odd reason, if you do not want to use ‘push’ method, but want to append an element at the end, we can use the ‘splice’ method.
We are passing myArray.length as the first parameter to the splice method as position, 0 as the number of elements we want to remove from that position and 4 as the value that we want to replace there. As there will be no element available at that position (last element index will be array length – 1, as the index starts from zero) , and we are also not removing anything, JavaScript simply inserts 4 there.
Adding an Element to an Array using ‘concat’ method
Generally we use the ‘concat’ method in JavaScript to merge two or more arrays. Though, it is generally used to merge arrays, we can also append values directly using this method
example:
Is there any other way to append an element at the end in JavaScript ?
Yes, there is yet another way to do it.
Appending an Element to an Array in JavaScript using ES6 Spread Operator
We can also use the newly available spread operator (…, three dots) to append elements to an array. Here is the code
In the above example, not just one (in this case 4), you can add as many elements as you want separated by commas.
Adding any Element to an Array at a specific position in JavaScript
We can use the ‘splice’ method to add an element at any specific position in an array. Earlier, we have seen how to add en element at the end using the ‘splice’ method, similarly, we can use it to add an element at any specific position.
example:
In the above example, we inserted a value 2 at position 1.
We have seen different ways to add an element to an array in JavaScript, if you know any other way, please mention it in the comments.
Leave A Comment