0

I was trying to multiply each of the values in an array by 2 and push the value to another array at each loop. I have no idea why the following code seems to triger an infinite loop which crashes the browser. I have other solutions to get the same result but I just wanted to know the root cause behind the crash so please educate me. Thanks!

multipliedBy([1,2,3], 2) //expected result: [1,2,3,2,4,6]

function multipliedBy(arr, num){
   var oldArr = arr;
   for(var i=0;i<arr.length;i++){
      oldArr.push(arr[i] * num);
   }
   return oldArr;
}
zanni222
  • 3
  • 1

2 Answers2

2

Try like this way with cloning the array instead of referring the same array while using push(),

console.log(multipliedBy([1,2,3], 2)) //expected result: [1,2,3,2,4,6]

function multipliedBy(arr, num){
   var oldArr = [...arr]; //clone using spread 
   for(var i=0;i<arr.length;i++){
      oldArr.push(arr[i] * num);
   }
   return oldArr;
}

Useful note from comment: Because oldArr and arr point on the same array, hence arr.length changes with every .push() - Andreas

A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
0

When you do var oldArr = arr; it is a reference to arr. In the loop you are looking at the length arr.length and when you push to oldArr, you are pushing to arr and the length keeps increasing so you keep looping.

function multipliedBy(arr, num) {
  var oldArr = arr.slice(0);
  for (var i = 0; i < arr.length; i++) {
    oldArr.push(arr[i] * num);
  }
  return oldArr;
}

console.log(multipliedBy([1, 2, 3], 2))

or if you do not want to clone the array, than just set it a variable before you alter it.

var oldArr = arr;
var len = arr.length;
for(var i=0; i<len; i++){
epascarello
  • 204,599
  • 20
  • 195
  • 236