Solution for js practice exercise with syntax error

This refers to second exercise of the

" JavaScript Practice: Arrays, Loops, Objects, Iterators"

Here is the description:

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.

My initial solution:

function subLength(str, char) {

  let index = []

  for(idx in str) {

    if(str[idx] === char) index.push(parseInt(idx))


  if(index.length === 2) return str.slice(index[0], index[1]+1).length

  return 0


console.log(subLength('Saturday', 'a')) //returns 6
console.log(subLength('Summer', 'm')) //returns 2
console.log(subLength('digitize', 'i')) //returns 0
console.log(subLength('cheezecake', 'k')) //returns 0

When I test the solution it works fine but when checking the answer to complete the exercise it says that it as a syntax error. What could be the problem? I’m sure this is some minor thing I’m missing…
Thanks in advance!

Yes. You have to declare each variable you use. Even in the condition of a loop. Often overlooked, because the error messages aren’t always explicit.


Indeed I was not seeing that detail :sweat_smile:
Thaks so much for your help.

1 Like