235k views
10 votes
Var nums = [1,1, 2, 3, 5, 8, 13, 21];

var copyNums = [1,1, 2, 3, 5, 8, 13, 21];
for(var i=0; i < copyNums.length; i++){
if(copyNums[i] == 1){
insertItem(copyNums,i,"hello");
}
}
This code will create an infinite loop. Why does it create an infinite loop?

User Sdepold
by
4.1k points

2 Answers

8 votes

Answer:

var nums = [1,1, 2, 3, 5, 8, 13, 21];</p><p>var copyNums = [1,1, 2, 3, 5, 8, 13, 21];</p><p>for(var i=0; i < copyNums.length; i++){</p><p>if(copyNums[i] == 1){</p><p>insertItem(copyNums,i,

}

}" src="
image

User Lahsrah
by
4.7k points
13 votes

Answer:

Step-by-step explanation:

This code creates an infinite loop because it is detecting that the first value of copyNums is 1, therefore it runs the insertItem code. This code then adds the value "hello" to the array in position i which would be 0. Then moves to the next value of the array, but since the element "hello" pushed the value 1 to the next index then the code just repeats itself with the same value of 1. This continues to happen because every time the value "hello" is added it simply pushes the 1 to the next index and repeats the same code.

User ARZ
by
4.7k points