How to write JavaScript array methods includes and join from scratch

·

1 min read

How to write JavaScript array methods includes and join from scratch

includes

Return true if the item is in the array otherwise, return false.

Array.prototype._includes = function(value, fromIndex = 0) {
    for(let i = fromIndex; i < this.length; i++) {
        if(this[i] === value) {
            return true
        }
    }

    return false
}

const numbers = [1,2,3,4,5]

console.log(numbers.includes(3))
// Output
// true
  • loop over array

  • if fromIndex is passed then start from fromIndex otherwise start from 0.

  • then return true if matches otherwise return false when the loop ends.

join

Return a string by concat all the elements with a comma , if no separator is provided.

Array.prototype._join = function(seperator = ',') {
    let str = ''

    for(let i = 0; i < this.length; i++) {
        if(i !== this.length - 1) {
            str += this[i] + seperator
        } else {
            str += this[i]
        }
    }

    return str
}

const fruits = ['apple', 'banana', 'mango', 'orange']
console.log(fruits._join('-'))
// Output
// 'apple-banana-mango-orange'
  • loop over an array of elements.

  • if the index is not the last then, attach the element with a separate string.

  • otherwise, add only the element.