Add and remove items in JavaScript array with push, pop, shift, unshift

Published: · Reading time: 2 min

JavaScript have native methods to add and remove items at the beginning and the end of array.

  1. Add item at the end push()
  2. Add item at the beginning unshift()
  3. Remove last item pop()
  4. Remove first item shift()

Add item at the end push()

The push() method adds one or more elements to the end of an array and returns the new length of the array.

const fruits = ['apple', 'banana', 'orange']

fruits.push('mango') // 4

console.log(fruits) // ['apple', 'banana', 'orange', 'mango']

Add item at the beginning unshift()

The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

const fruits = ['apple', 'banana', 'orange']

fruits.unshift('mango') // 4

console.log(fruits) // ['mango', 'apple', 'banana', 'orange']

Remove last item pop()

The pop() method removes the last element from an array and returns that element.

const fruits = ['apple', 'banana', 'orange', 'mango']

fruits.pop() // 'mango'

console.log(fruits) // ['apple', 'banana', 'orange']

Remove first item shift()

The shift() method removes the first element from an array and returns that removed element.

const fruits = ['apple', 'banana', 'orange', 'mango']

fruits.shift() // 'apple'

console.log(fruits) // ['banana', 'orange', 'mango']
Like this article? Share it on:

Top online courses in Web Development
Top online courses in Web Development