JavaScript code challenge subLength

Hey guys,
I’ve been killing myself here and I cant figure out why my code isn’t working. I am completely off from what the solution is somehow, but I’m trying to find the hole in my code and why its not passing the criteria. Please see below for link and code block. Thanks in advance.

Click here! Its the second one

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 = (word, letter) => { let letters = [] for (w in word) { letters.push(word[w].toLowerCase()) } let a = letters.indexOf(letter) let b = letters.indexOf(letter, a + 1) let dup = letters.indexOf(letter, b + 1) if(a != -1 && dup == -1) { let c = b - a +1 return c } else { return 0 } } console.log(subLength("Supercalifragalisticespialadocious", "p")); // returns 21 console.log(subLength("Supercalifragalisticespialadocious", "s")); // returns 0 console.log(subLength("Supercalifragalisticespialadocious", "x")); // returns 0 console.log(subLength("Supercalifragalisticespialadocious", "e")); // returns 18 console.log(subLength('Saturday', 'a')); // returns 6 console.log(subLength('summer', 'm')); // returns 2 console.log(subLength('digitize', 'i')); // returns 0 console.log(subLength('cheesecake', 'k')); // returns 0

Hi Scotty,
your code runs just fine and returns the expected result.
But you should add the keyword var or let in your loop condition:

for (let w in word)

w is a variable and should be initialized.
When I paste your code in my sandbox with the keyword added, it passes.

1 Like

Thank you Mirja_t,
I’m trying to break my habits lol also notice my lack of ; at the end of a statement… It’s tough when your used to something else to remember the little things.

1 Like