JavaScript Practice: Why does the variable len equal to -1?

Link to JavaScript Practice: Arrays, Loops, Objects, Iterators Question 2: https://www.codecademy.com/paths/full-stack-engineer-career-path/tracks/fscp-javascript-syntax-part-ii/modules/fecp-practice-javascript-syntax-arrays-loops-objects-iterators/articles/fecp-javascript-practice-arrays-loops-objects-iterators

  let charCount = 0;
  let len = -1;
  
  for (let i=0; i<str.length; i++) {
    if (str[i] == char) {
      charCount++;
      if (charCount > 2) {
        return 0;
      }
      if (len == -1) {
        len = i;
      } else {
        len = i - len + 1
      }
    }
  }
  if (charCount < 2) {
    return 0;
  }

  return len;
};

Where do you get it that len=-1? Did you write this code, or is it the solution code?

Where do you get it that len=-1 ?
Solution Code

I am wondering the same thing. The following block of code is hurting my brain:

I’m assuming that we’re still iterating through the string forwards, so as this happens, I’m also assuming that the value of len is getting updated. The formula of len = i - len + 1 in order to calculate and store the number of characters is really confusing to me. Any help with this?
Thanks!

  • Ian