DEV Community

Cover image for Array Methods in JS - push and pop
Shubham Tiwari
Shubham Tiwari

Posted on • Edited on

Array Methods in JS - push and pop

Hello Today i will be discussing about inbuilt push() and pop() method of Arrays.

Let's get started...

Push - It is used to insert an element at the end of the array.
Pop - It is used to remove the element from the array.

Code Example -

const array = [1,2,3,4,5];
const array2 = ["This","is","array2"]

array.push(6) //single element insertion
array.push(7,8,9) // multiple element insertion
array.push("BOOTSTRAP5") // string element insertion
array.push("TAILWINDCSS","REACT JS") //multiple string element insertion
array.push([10,11]) // number array insertion
array.push(["NODE JS","MONGO DB"]) // string array insertion
array.push([[12,13],[14,15]]) // 2-d array insertion
array.push({name:"shubham",age:21}) // Object insertion
array.push(array2) // array stored in a variable then inserted 
array.push(undefined,null) // undefined and null insertion
array.push(true,false) // Boolean insertion
array.push(array) // [Circular *1]

console.log(array)

array.pop() // pop out the last element
array.pop() // pop out the last element
Enter fullscreen mode Exit fullscreen mode

Output -

[
  1,
  2,
  3,
  4,
  5,
  6,
  7,
  8,
  9,
  'BOOTSTRAP5',
  'TAILWINDCSS',
  'REACT JS',
  [ 10, 11 ],
  [ 'NODE JS', 'MONGO DB' ],
  [ [ 12, 13 ], [ 14, 15 ] ],
  { name: 'shubham', age: 21 },
  [ 'This', 'is', 'array2' ],
  undefined,
  null,
  true,
  false,
  [Circular *1]
]

After popping 2 times
[
  1,
  2,
  3,
  4,
  5,
  6,
  7,
  8,
  9,
  'BOOTSTRAP5',
  'TAILWINDCSS',
  'REACT JS',
  [ 10, 11 ],
  [ 'NODE JS', 'MONGO DB' ],
  [ [ 12, 13 ], [ 14, 15 ] ],
  { name: 'shubham', age: 21 },
  [ 'This', 'is', 'array2' ],
  undefined,
  null,
  true
]
Enter fullscreen mode Exit fullscreen mode
  • As you can see we can push many tyes of elements in the array.
  • At the last push, we have pushed the array itself and it returned "[Circular *1] , Circular reference is a references where an object references itself directly or indirectly through an object.
  • After using pop() two times, the last two elements are removed.

THANK YOU FOR CHECKING THIS POST
^^You can help me by some donation at the link below Thank you👇👇 ^^
☕ --> https://www.buymeacoffee.com/waaduheck <--

Also check these posts as well
https://dev.to/shubhamtiwari909/javascript-map-with-filter-2jgo

https://dev.to/shubhamtiwari909/e-quotes-3bng

https://dev.to/shubhamtiwari909/deploy-react-app-on-netlify-kl

Top comments (2)

Collapse
 
zeeshanali0704 profile image
ZeeshanAli-0704

nice

Collapse
 
shubhamtiwari909 profile image
Shubham Tiwari

Thank you