Add and remove items in JavaScript array with push, pop, shift, unshift
JavaScript have native methods to add and remove items at the beginning and the end of array.
- Add item at the end push()
- Add item at the beginning unshift()
- Remove last item pop()
- 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']