Part of function seems not to be executing

Hello. I’m doing some practice with Arrays, Loops, Objects, Iterators on JavaScript Full-Stack Engineer course.
https://www.codecademy.com/paths/full-stack-engineer-career-path/tracks/fscp-javascript-syntax-part-ii/modules/fecp-practice-javascript-syntax-arrays-loops-objects-iterators/articles/fecp-javascript-practice-arrays-loops-objects-iterators

There’s this second challenge:

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.

Examples:

subLength('Saturday', 'a'); // returns 6
subLength('summer', 'm'); // returns 2
subLength('digitize', 'i'); // returns 0
subLength('cheesecake', 'k'); // returns 0

I actually don’t have problem coming up with a solution posted below. I wanted to log values of all indexes to check if they’re correct, and it seems that all that part of function after if…else statement is not executed. I tried logging, some math operations, other if statements and nothing works. Putting all that before if…else worked, but I’m just wondering why this piece of code doesn’t.

function subLength(sentence, letter){
  sentence.toLowerCase();
  const firstIndex = sentence.indexOf(letter);
  const secondIndex = sentence.indexOf(letter, firstIndex + 1);
  const thirdIndex = sentence.indexOf(letter, secondIndex + 1);
    if (firstIndex >= 0 && secondIndex && thirdIndex === -1){
    return secondIndex - firstIndex + 1;
  } else {
    return 0
    };
    console.log(firstIndex);
    console.log(secondIndex);
    console.log(thirdIndex)
    };

console.log(subLength('saturday', 'a'))

I appreciate all the help. Thank You in advance.

Notice how you have return statements within the if…else block? All code after a return statement is reached does not execute, and, since either of the return statements will always be reached, none of the code after that block will run:

function some_func(){
  console.log("This will be printed");
  return "Nothing after this will be executed";
  console.log("This won't be printed to the console.");
}
2 Likes

Thank You kindly. I guess, I didn’t realize it works this way.

1 Like