Javascript: subLength() code challenge

Hi all! I’m new at coding and I have encountered a code challenge that I can’t solve. My code is returning the “correct” values as far as I can tell, but it is not passing the exercise. Any help would be highly appreciated.

My code is pasted below:

let counter=0;
let result=0;

const subLength = (str,char) => {
  // split into string array

  // count the repetitions
  stringArray.forEach(item => {
    if (item === char){

  // evaluate if num of reps is 2
  if (counter === 2) {
    result = stringArray.lastIndexOf(char)-stringArray.indexOf(char)+1
   // set result to 0 if not right amount of reps
    else if (counter != 2){
    result = 0;

  return result;

When I test my code using console.log(subLength(‘funny’,‘n’)) it prints 2 to the console. However, when I click ‘check answer’ it gives me the error Tested subLength('funny', 'n') and it did not return 2 . Can you help me understand what went wrong in my code?

Link to the code challenge

Try testing your code more than once with the same input (without restarting the program).

console.log(subLength("funny", "n"));
console.log(subLength("funny", "n"));

Thank you very much! You made me realize I had placed the variable declarations incorrectly. It worked as soon as I placed them within the function. I really appreciate the help.

1 Like