Help to fix this one in JS

I need help. My program in 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.

Using a variant of your array, I did something a bit different.

const array = [
  "Don't click me",
  "I said don't click me",
  "This will be the last time I will tell you. Don't click me",
  "I'll cut your hands off if you click me one more time",
  "Moron, now you are toast",
  "C'mon man, seriously?",
  "Please bro, m sorry OK"
let i = 1;
const myFunction = () => {
  if (i === array.length) {
    i = 0;
  return array[i++];

I added the “Don’t click me” into the array, because I assume you actually want to start over with what you start with in the button text.

1 Like

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