Arrays have been a very useful data type in all the programming languages. They are usually used to describe a collection of elements, values or variables. A lot of us might have come across scenarios where we had to insert a new value into the javascript array. Let us take a look at how to append or add new values to an existing Array using JavaScript.
Add new values to Array using Array.push()
You can add values to an existing array using Array.push()
method available in JavaScript. The Array.push()
method accepts comma separated values as parameters and appends the new values to the end of the Array.
The Array.push() method alters an Array by appending the value to it and returns the new length of the Array.
The syntax of Array.push() method is :
arr_name.push(value1, value2, value3, ... , valueN);
//where the "arr_name" is an existing array's name.
Let’s take a look at another example:
var colors = ["red", "green"];
var totalColors = colors.push("blue", "yellow");
console.log(colors); // ["red", "green", "blue", "yellow"]
console.log(totalColors); // 4
Please note that the array.push()
method appends the values to the end of the array. If you would like to insert the values at the beginning of the array then please use array.unshift();
Hope you are clear about the usage of Array.push()
method. Do let us know about your queries and also do not forget to Like and Share this page on Facebook and Twitter.