subLength project

Continuing the discussion from I have Strangest bug in my code for subLength js problem, it's really weird:

Hi, Could someone help?
My code doesn’t work. It returns 0.

// Write function below
const subLength = (word, letter) => {
let occurance = 0;
const letterIndices = ;
let letterLength = 0;
/if (typeof word !== ‘string’ || letter.length !== 1) {
console.log(‘Please choose a word and a letter’);
} else {
/
for (let i = 0; i < word.length; i++) {
if (word[i] === letter) {
letterIndices.push(i);
}
if (letterIndices.length < 2) {
return 0;
} else if (letterIndices.length = 2) {
return letterLength = letterIndices[1] - letterIndices[0] + 1;
} else {
if (letterIndices.length > 2) {
return 0;
}
}
}
}
console.log(subLength(‘Saturday’, ‘a’));

Right here you’ve put “if letterIndices length is less than 2, then return 0”. Problem is that letterIndices length starts off at 0, so on first pass it immediately returns 0 from the function. Technically the code is working correctly, but some work is needed to get it to do what you want.

1 Like

Hi Adam,
Thank you so much for the explanation. I understand now.
That was really helpful.

Many Thanks!
Sharon.