How to Add a Value to an Array in JavaScript

From WikiHTP
Revision as of 06:34, 28 January 2019 by Admin (talk | contribs) (1 revision imported)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

It is possible to add variables to an array that already contains them in JavaScript. The Array class provides the necessary methods by default. The latter differ according to the type of values that we want to add. Here we are about to see how to add a value to an array in JavaScript.

Using push() Method

To add a value to an array, simply use the push() method. This method returns the length of the array once the new values are added.

var myArray = [x, y, z];
var length = myArray.push(a);
console.log (myArray); // This command will display [x, y, z, a]
console.log (length); // This command will display 4

The push() method can take multiple values ​​later as arguments. It accepts as many values ​​as you want. These values ​​are added after the table in the same order as the order of the parameters.

var myArray = [x, y, z];
var length = myArray.push(a, d, b);
console.log (myArray); // This command will display [x, y, z, a, d, b]
console.log (length); // This command will display 6

Using concat() Method

If the variables you want to add are contained in an array, then use the concat() method. Its operation is different from the push() method. It takes as the parameter the array to concatenate and returns a result the array resulting from the concatenation. The two starting tables are not affected.

var myArray = [x, y, z];
var mySecondArray = [a, d, b];
var arrayTotal = myArray.concat(mySecondArray);
console.log (myArray); // This command will display [x, y, z]
console.log (arrayTotal); // This command will display [x, y, z, a, d, b]

About This Tutorial

This page was last edited on 28 January 2019, at 06:34.