To add/push items or elements to the end of the array, you can use the push()
array method in JavaScript.
Suppose we have an array of names like this,
// Names Array
const namesArr = ["Roy", "Aleena", "Mary"];
Let's add another name Laila
to the end of the array using the push()
array method. The method accepts values as arguments to be added to the end of the array.
// Names Array
const namesArr = ["Roy", "Aleena", "Mary"];
// Add name Laila
// using the push method
namesArr.push("Laila");
console.log(namesArr); // ["Roy","Aleena","Mary", "Laila"]
If you want to add more than one value at the same time, You can pass those values as arguments to the method like this,
// Names Array
const namesArr = ["Roy", "Aleena", "Mary"];
// Add names Laila, Meera, Lily
// at the same time
// using the push method
namesArr.push("Laila", "Meera", "Lily");
console.log(namesArr); // ["Roy", "Aleena", "Mary", "Laila", "Meera", "Lily"]
- The method returns the number of elements in the array after adding the item/items.
See this example live in JSBin.