Search code examples
javascriptarraysforeachprototype

Extending Array.prototype crashes


I was trying to solve the following problem which I got on a blog but the program crashes. What could be the reason? and is there any means of solving it? I have read warnings not to extend builtin objects, if that's the case, what could be the reason associated with this specific example.

const a = [1, 2, 3, 4, 5];

//this is what I tried
Array.prototype.multiply = function() {
  for (m of this) this.push(m * m);
}

a.multiply(); //this should not be changed
console.log(a); // [1, 2, 3, 4, 5, 1, 4, 9, 16, 25] (expected output)


Solution

  • When you push the value to same array during loop, you end up in infinite loop, create a temp array push value to it, in the end add it to this

    const a = [1, 2, 3, 4, 5];
    
    //this is the what I tried
    Array.prototype.multiply = function() {
      let newArr = []
      for (const m of this) {
        newArr.push(m * m)
      }
      this.push(...newArr)
    }
    
    a.multiply();
    console.log(a);

    That being said you should not override the prototype simply use a function and pass the parameters

    const a = [1, 2, 3, 4, 5];
    
    function multiply(arr) {
      return [...arr, ...arr.map(a => a * a)]
    }
    
    console.log(multiply(a));