Question on: JavaScript Practice: Arrays, Loops, Objects, Iterators

Hi there, I am going through this javascript practice module and I am having a hard time wrapping my head around finding the length in the exercise below. I have posted the solution and am trying to logically understand it. here are my questions:

why are we initially setting len = -1; ?
-why negative one as opposed to other numbers.

Also, i am hoping someone may be able to explain exactly what this bit of code is saying?

  • if (len == -1) {
    len = i;
    } else {
    len = i - len + 1
    }

thank you for any help and insights you may have! The question and code are below:

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.

const subLength = (str, char) => {
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;
};

console.log(subLength(‘abra’, ‘a’))

Setting it to the negative number is just a common way of saying, “This thing has not happened yet,” in JavaScript. You could technically set it to any number in this case, though this is not always true.

As for that bit of code, it is essentially saying:

If the length between characters (the one we’re searching for) is -1, then it has never changed and this is the first time we’ve seen the character. So we should set the length to the current index.

Else, we must be seeing the second instance of the character, so to find the distance between the first instance and this instance, we minus the length from the current index and add 1.

3 Likes

This is so frustratingly simple and clever. Thank you for explaining.