Help to fix this one in JS

I need help. My program in https://codepen.io/BlazingIce/pen/oNNNjPW gives out undefined and I failed to loop it such that it starts from begining at the end. Silly one but please help.

The culprit is the following line:

result = array[array.indexOf(result) + 1];

When the last element of array is assigned to result, then next time the function runs, you end up trying to access an index that is not there which results in result being assigned the value undefined. The + 1 is what does it.

For example, when result is “Please bro, m sorry OK”, then the line above is:

result = array[array.indexOf("Please bro, m sorry OK") + 1];

which is:

result = array[6 + 1];

which is:

result = array[7]; // there is no element at index 7, because there are only 7 elements and arrays in JavaScript are zero-indexed.

Also, there really is no need to use a for loop here. You can just keep track up the current index in a variable and keep increasing the index until the index is equal to the length of the array minus 1.

1 Like

Thanks a million. I will try to fix it…

I fixed it. Useless app but I enjoyed and learned.
https://codepen.io/BlazingIce/pen/oNNNjPW

Thank you. I feel like this is how I learn more that repeated challanges; “discussion”.