How to add an element to an array in JavaScript?
In this post, I have listed some of the easy ways to add elements to an array in JavaScript. There are several methods for adding new elements to a JavaScript array which are explained with examples below.
1. Add element in beginning of an Array
The unshift()
method will add the element to the start of the array. While its twin function shift()
used to remove first element in an array.
var list = ["Boo", "Zoo", "Foo", "Cow", "Bow", "Saw"]; //To add one element list.unshift("Bass"); //Result: ["Bass", "Boo", "Zoo", "Foo", "Cow", "Bow", "Saw"] //To add multiple element list.unshift("Bass", "Band"); //Result: ["Bass", "Band", Boo", "Zoo", "Foo", "Cow", "Bow", "Saw"]
2. Add element in end of an Array
The push()
method will add the element to the end of the array. While its twin function pop()
used to remove last element in an array.
var list = ["Boo", "Zoo", "Foo", "Cow", "Bow", "Saw"]; //To add one element list.push("Bass"); //Result: ["Boo", "Zoo", "Foo", "Cow", "Bow", "Saw", "Bass"] //To add multiple element list.push("Bass", "Band"); //Result: [Boo", "Zoo", "Foo", "Cow", "Bow", "Saw", "Bass", "Band"]
3. Add element in specified position
If you want to place the element in specific index within the array or beginning/end of any element in array. This can be done by splice()
method.
var list = ["Boo", "Zoo", "Foo", "Cow", "Bow", "Saw"]; // at index position 1, remove 0 elements, then add "Code" to that position //To add one element list.splice( 1, 0, "Code"); //Result: ["Boo", "Code", "Zoo", "Foo", "Cow", "Bow", "Saw"]; //To add multiple element list.splice( 1, 0, "Code", "Bar", "Jar"); //Result: ["Boo", "Code", "Bar", "Jar", "Zoo", "Foo", "Cow", "Bow", "Saw"];
4. Add an array to an new Array
concat()
method makes this simple. This method will return the combined array with the specified array.
var list = ["Boo", "Zoo", "Foo", "Cow", "Bow", "Saw"]; //To add one element Console.log(list.concat("Soo")); //Result: ["Boo", "Zoo", "Foo", "Cow", "Bow", "Saw", "Soo"]; //To add multiple element Console.log(list.concat(["Soo", "Ban", "Jam"])); //Result: ["Boo", "Zoo", "Foo", "Cow", "Bow", "Saw", "Soo", "Ban", "Jam"];
5. Add element in particular index.
We can also directly manipulate the array, without the use of any array methods, by referring to the index position within the array.
var list = ["Boo", "Zoo", "Foo", "Cow", "Bow", "Saw"]; list[5] = "Poop"; //["Boo", "Zoo", "Foo", "Cow", "Bow", "Poop"] list[ list.length ] = "Baz"; //["Boo", "Zoo", "Foo", "Cow", "Bow", "Saw", "Baz"]