JavaScript Code Challenge : subLength()

Hello, I am attempting to do this challenge and on the first step of my code, I just want the code to identify how many instances of letter appear in the string parameter. However, I cant get it to work. I’ve been stuck on it the whole day and I cant find what’s wrong with it! It should output 2 but it keeps on outputting 0!

// Write function below
const subLength = (string, letter) => {
  let occur = 0; 
  for (let i = 0; i < string.length; i++){
    if(string[i] === letter) {
    occur ++;
    }
  return occur;
  }
};



console.log(subLength("hello", "l"));

The return statement is what is causing your issue. It is currently within the scope of the for loop. The code runs, checks if the letter matches and then immediately returns occur.

Move the return statement outside of the for loops scope and your should be in good shape.

const subLength = (string, letter) => {
  let occur = 0; 
  for (let i = 0; i < string.length; i++){
    if(string[i] === letter) {
    occur ++;
    }
  }
  return occur;
};

1 Like

THANK YOU!!!
you have taught me a valuable lesson!
I appreciate it !

1 Like