"Double check your code. It likely has a syntax error" on functioning code

Hi,
I’m on the “Practice Javascript Syntax: Arrays, Loops, Objects, Iterators” part in the Front end career path.
In the Article after the lessons, there are three “challenges”. I just finished challenge number 2. It returns the correct value every time, but when I check the answer, I get a message saying “Double check your code. It likely has a syntax error”

Link to challenge: Javascript Syntax Article

Here is my code:

// Write function below
function subLength(string, char) {
  charArray = string.split('');
  let charCount = 0;
  let charPos1;
  let charPos2;
  for (character of charArray) {
    if (character === char) {
      charCount += 1;
    } else {
      continue;
    }
  }
  if (charCount === 2) {
    for (character of charArray) {
      if (character === char) {
        if (charPos1 !== undefined) {
          charPos2 = charArray.indexOf(character, charPos1 + 1);
        } else {
          charPos1 = charArray.indexOf(character);
        }
      } else {
        continue;
      }
    }
  } else {
    return 0;
  }
  return charPos2 - charPos1 + 1;
}

console.log(subLength('Saturday', 'a'));

I’m aware that it’s probably possible to write this in much less code, but as I’m still new to Javascript (and coding in general), I consider myself forgiven :wink:

I would very much appreciate if somebody could point out what could be wrong that makes this code fail as an approved solution.

Thanks a lot!
Phil

The above is not a mistake, per se, yet it jumps out owing that as defined it is a global, not a local variable. Remember to scope all the variables in your functions.

const charArray = ...

Superfluous, as in, not needed. Still, not a mistake.

As near as one can tell, there are no errors. It may just be the SCT not expecting us to log any results. Remove the last line and Run. Then check answer again.

As far as I can see, you have not declared the variable character. That might also be a cause of trouble…

1 Like

Thank you mtf!
The language I learned first was Python, so I am still defining variables without let/const by habit. Thanks.

I added the else {continue;} because my code was not working as intended before. I assume something else I did actually solved the problem, and not this :smiley:

Thank you!

1 Like