Trouble with the function sublength () practice

Hi there, I have been stuck on this one problem for over an hour. While my solution is different than the solution provided, It still returns the proper value when I log the function to check my work. Can someone help me see why my solution wont pass?

let counter = 0;
const subLength = (string, char)=> {
for (let i = 0; i < string.length; i++){
  if (string[i] === char) {
if (counter === 2) {
  let length = (string.lastIndexOf(char) - string.indexOf(char) + 1)
  return length
 if (counter !==2) {
  return 0;


console.log(subLength('funny', 'n'))

Here is the link to the exercise:

Hi @mega5423686859
the problem here is that your counter variable is located outside of the function scope. Your function only works as expected for the first function call because you don’t reset the counter after each invocation. Test it with the stack of function calls provided and log the counter.

1 Like

I see, thank you for the insight!

1 Like

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.