Practice javascript question

Can anyone help me? In the exercise below I expect the outcome of 6: the length between the 2 characters ‘a’ including the characters itself. When I simply remove ‘return 0’ it works… I know that the first time it loops, it doesn’t past the test ‘letterCount == 2’, but I don’t know the solution…

After 2 hours of puzzling my options are zero…

const subLength = (string, character) => { var letterCount = 0; for (var position = 0; position < string.length; position++) { if (string[position] == character) { letterCount += 1; console.log(letterCount); } else if (letterCount == 2) { return (string.lastIndexOf(character) + 1) - (string.indexOf(character)); } else { return 0; } } }; console.log(subLength('saturday', 'a'));

your conditions are a little odd: If the first letter in the string is not equal to the character, it will skip the first block since the condition is not fulfilled.
It will also skip the second block, because the letter count is 0, not 2.
So it will enter the else block and return 0. Due to the return keyword it will leave the for loop and be done.

thanks for the reply… the solution was (as you knew already) to put ‘return 0’ outside the loop… :slight_smile: