How to add new value to an array in JavaScript using Array.push() ?

Posted underJavascript

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.

TaggedAPIArrayJavascript – Read tutorials related to JavaScript, jQuery, HTML5, CSS3 and more !

Cover Image for How to check if checkbox is checked in jQuery?

How to check if checkbox is checked in jQuery?

It is very easy to check if a checkbox is checked in jQuery using the .is() or .prop() method of jQuery combined with the ‘:checked’ selector. There are other ways too like checking for the attribute checked value, however, they aren’t very reliable. The easiest and most stable way to check if checkbox is checked … Read more

Cover Image for [Solved] Attempted import error: ‘Switch’ is not exported from ‘react-router-dom’

[Solved] Attempted import error: ‘Switch’ is not exported from ‘react-router-dom’

You might be facing an “Attempted import error: ‘Switch’ is not exported from ‘react-router-dom’ ” error if you are using the react-router-dom package version 6. This error is caused due to using the older switch syntax of the react-router-dom. From version 6 onwards, the react-router-dom has replaced “Switch” with “Routes”. Let us take a look … Read more