How to write JavaScript array methods push and pop from scratch
DevBitByte
1 min read
push
Add an element to the end of the array(JS has a dynamic array).
Array.prototype._push = function(...values) {
for(let i = 0; i < values.length; i++) {
this[this.length] = values[i]
}
return this.length
}
const fruits = ['apple', 'mango']
console.log(fruits._push('banana', 'orange'))
// Output
// 4
use the rest operator(
...
) to store valuesloop the values and store the values in our array
return length of an array
pop
Remove the last element from an array.
Array.prototype._pop = function() {
if(this.length === 0) return
const lastElement = this[this.length - 1]
this.length--
return lastElement
}
const fruits = ['apple', 'mango', 'orange', 'banana']
console.log(fruits._pop())
// Output
// banana
store the last element to a variable
decrease the array length
returns the last element
0
Subscribe to my newsletter
Read articles from DevBitByte directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by