How to write JavaScript array methods push and pop from scratch

·

1 min read

How to write JavaScript array methods push and pop from scratch

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 values

  • loop 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