2

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)

2 Answers 2

3

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));

Sign up to request clarification or add additional context in comments.

2 Comments

As for the second method, I know there are much simple ways of doing it but "a.multiply();" is not part of my solution, it was part of the original question.
@Addis always happy to help :) yeah the second one is to mention that we should be taking simple paths unless we are forced to take the odd one
1

Pushing a new value into an array in the middle of a for ... of loop creates an infinite loop as the loop includes the new values. You can use forEach instead as that ignores the new values added:

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

Array.prototype.multiply = function() {
    this.forEach(v => this.push(v*v));
}

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.