How is this an infinite loop?

Tell us what’s happening:

Why is this an infinite loop? (FCC console reports an infinite loop in line 7, I just can’t see how that is)

Your code so far


function reverseString(str) {

let array = str.split("");
console.log(array.length);
let array2 = [];

for(var i = 0; i < array.length; i++){
  array2 = array.unshift(i)
}

return array2.toString();


}

reverseString("hello");

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.5 Safari/605.1.15.

Challenge: Reverse a String

Link to the challenge:

For loop is constantly adding elements to array, so variable i will never reach array.length, it will always be less than array.length.

2 Likes

The unshift() method adds one or more elements to the beginning of an array

1 Like

This link shows you what will happen more preciesly which might help you understand what is happening in the code excatly: http://pythontutor.com/visualize.html#mode=edit