In this blog post you’ll learn JavaScript push() Method. Method to add new elements inside array.
Description:
Push() method adds a new item to the array.
Push() method adds an item at the end of the array.
Push() method changes the length of the array.
Syntax:
JavaScript
array.push(item1,item2,item3,item4,.....,itemN);
Example 1:
Add new items to the array.
HTML
let fruits_array = ["Mango", "Orange", "Apple", "Banana", "Grapes"];
fruits_array.push("Pomogranate", "Pineapple");
document.write(fruits_array);
// Output:
// Mango,Orange,Apple,Banana,Grapes,Pomogranate,Pineapple
Example 2:
Add new items to the empty array from another array. Or Copy all items from one array to another array.
HTML
let fruits_array = ["Mango", "Orange", "Apple", "Banana", "Grapes"];
let new_array = [];
for (let i = 0; i < fruits_array.length; i++) {
const element = fruits_array[i];
new_array.push(element);
}
document.write(new_array);
// Output:
// Mango,Orange,Apple,Banana,Grapes
So that's how the JavaScript push() method works. If you have any query or suggestion feel free to write in the comment section.
Share your thoughts.