push() Method in JavaScript.
•JavaScript•1 min read

javascriptpush methodarray methods
push() method is a built-in method in javascript, which is used to add one or more elements to the end of an array.
push() Method in JavaScript.
push()method is a built-in method in javascript, which is used to add one or more elements to the end of anarray.- It modify the original array.
- Like here this is a
cart arraywhich contains some items in it.
let cart = ['shirt', 'jeans'];For showing the all items, use forEach() method, we will discuss forEach() method later.
let cart = ['shirt', 'jeans'];
cart.forEach(item => {
document.write(item + "<br>");
})
// Output:
shirt
jeansNow it show all elements shirt, jeans.
- Then add one more item in the
cart array, by write,cart.push(), and pass the item shoes.
let cart = ['shirt', 'jeans'];
cart.push('shoes');
cart.forEach(item => {
document.write(item + "<br>");
})
// Output:
shirt
jeans
shoesnow shoes is add in the end.
- Again add more than one item in the cart by write,
cart.push(), and pass the items laptop and mobile.
let cart = ['shirt', 'jeans'];
cart.push('shoes');
cart.push('laptop', 'mobile');
cart.forEach(item => {
document.write(item + "<br>");
})
// Output:
shirt
jeans
shoes
laptop
mobileagain this 2 item laptop and mobile is added in the end.
- We can also add variable in an
arraybypush()method. - Like here we take item variable,
let item = 'bag'. - Now we add this to the cart, by write,
cart.push(), and pass the variableitem.
let cart = ['shirt', 'jeans'];
cart.push('shoes');
cart.push('laptop', 'mobile');
let item = "bag";
cart.push(item);
cart.forEach(item => {
document.write(item + "<br>");
})
// Output:
shirt
jeans
shoes
laptop
mobile
bagnow the item also added in the end.



