push() Method in JavaScript.

JavaScript1 min read
push() Method in JavaScript.
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 an array.
  • It modify the original array.
  • Like here this is a cart array which 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 jeans

Now 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 shoes

now 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 mobile

again this 2 item laptop and mobile is added in the end.

  • We can also add variable in an array by push() method.
  • Like here we take item variable, let item = 'bag'.
  • Now we add this to the cart, by write, cart.push(), and pass the variable item.
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 bag

now the item also added in the end.