# Finding the length between 2 elements

Hi there!

I’m really struggling to understand the following code…

The question: 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.

the code I’m analysing:

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;
``````

};

I’ve been playing around with the code and for the life of me cannot figure out what does the Len represent?
I think it has something to do with the length of where the first index meets the condition but I don’t understand why it has to start at -1? when I replace -1 with 0, the outputs still the same.

Would really appreciate anyone who can help!

Thank you!

Hi @cindycheung
welcome to the forums!
len initially represents the position of the targeted character in the string (`str[len]`). So it is initially set to -1, because 0 would already represent the first position of a string.
When the condition `len == -1` is fulfilled, `len` is set to the position of the first occurence of the passed character.
When the else is entered, len is set to the count of letters between the two passed characters.
Run the code with different strings with the consoles, maybe that helps you understanding what happens:

``````if (len == -1) {
len = i;
// first occurence of character
// len = position of first targeted character in string
console.log(`first hit: str[i] === \${char}[\${i}], len === \${len}`);
} else {
len = i - len + 1
console.log(`second hit: str[i] === \${char}[\${i}], len === \${len}`);
// second occurence of character
// len = position of second targeted character in string minus position of first targeted character + 1
}
``````
1 Like