JavaScript -JavaScript Practice: Arrays, Loops, Objects, Iterators

Hi all!

I’m trying to solve the Q2 of the JavaScript Practice and I have gotten this far. Below is my code for subLength function.

" 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."

Somehow, when I run this code, for the word “digitize” and “cheesecake” it doesn’t return “0” and instead, it returns nothing.

Could anyone help?



// Write function below
const subLength = (word, letter) => {
let lowerCaseWord = word.toLowerCase();
let counter = 0
for (let x of word) {
if ( x === letter) {
counter += 1
if (counter === 2) {
let slicedWord = word.split(letter)
console.log(slicedWord[1].length + 2)
} else {
return 0

subLength(‘Saturday’, ‘a’); // returns 6
subLength(‘summer’, ‘m’); // returns 2
subLength(‘digitize’, ‘i’); // returns 0
subLength(‘cheesecake’, ‘k’); // returns 0
subLength(‘funny’, ‘n’) // returns 2

you have
console.log(slicedWord[1].length + 2)
but maybe it should be
return slicedWord[1].length + 2
because something needs to be returned there.

1 Like

Ah! Thank you! I put console.log to see what it was generating but now that I changed it back, I passed the quiz! I guess I didn’t see “0” for “digitize” and “cheesecake” because I didn’t put console.log for those that return 0!

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.