JavaScript Practice: Arrays, Loops, Objects, Iterators - subLength Exercise

This exercise’s challenge is the following: “Write a function subLength() that takes 2 parameters, a string and a single character. The function should search the string for the two occurrences of the character and return the length between them including the 2 characters. If there are less than 2 or more than 2 occurrences of the character the function should return 0.

I don’t understand why the following code does not work. I clicked “Check Answer” and it says there might be a syntax error. However, I tried logging the examples given, the function ran without error, and they all logged correctly.

const subLength = (word, char) => {
  charCount = word.split(char).length - 1;

  if (charCount !== 2) {
    return 0;
  } else {
    return word.lastIndexOf(char) - word.indexOf(char) + 1;

console.log(subLength('Saturday', 'a')); // returns 6
console.log(subLength('summer', 'm')); // returns 2
console.log(subLength('digitize', 'i')); // returns 0
console.log(subLength('cheesecake', 'k')); // returns 0

I’ve found that the generic “syntax error” message in the interactive articles is usually caused by using a variable that wasn’t declared with let, const, or var.

In this case, you set the value of charCount that way. JavaScript allows this so it’s working when you run the code, but the test behind the scenes that Codecademy uses is stricter. It’s a best practice too, though it would be nice if the error message indicated what was happening for seemingly working code.

1 Like