Help With Codecademy Exercise

Hey, I was on the practice JavaScript, arrays, loops, objects, and iterators, and I ran into this exercise that’s got me stuck. The instructions are:

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

Here’s my code:

const subLength = (word, character) => {
  let counter = 0; 
  let charcount = 0; 
  for (let i = 0; i < word.length; i++){
    if (word[i] === character){
      counter++; 
      while (word[i] != character){
        charcount++; 
      }
    }
  }
  if (counter > 2 || counter < 2){
    return 0; 
  }else{
    return  charcount; 
  } 
}

console.log(subLength('computation', 'o')); 

All I’ve been getting are 0’s all day.

Thanks!

This is why you’re getting 0’s all day:

The while loop condition can’t possibly evaluate as true because the code is only reached if word[i] === character. Your charcount will always be 0. Also note that even if it did evaluate as true, it would cause an infinite loop, so be careful of that.

Hopefully this is a push in the right direction so you can try other strategies

Hey selectall thanks for the help! I approached this a different way, but the console is not returning anything.

// Write function below
const subLength = (word, letter) => {
  let charcount = 0;
  let counter = 0;  
  for (let i = 0; i < word.length; i++){
    for (let j = 1; j < word.length; j++){
      if (word[i] === letter){
        counter++;
        while (word[j] != letter){
          charcount++; 
        }
      }
    }
  }
  if (counter > 2 || counter < 2){
    return 0; 
  }else{
    return charcount; 
  }
};

console.log(subLength('computation', 'o')); 

Am I in some sort of infinite loop?

Indeed you are. Check here:

Once it enters this while loop, there is no way to get out. The operands of your conditional never change values, so they’ll always evaluate as the same and keep counting.

1 Like

You were closer the first time. The while loop in the original version should be an if block and nested in the for loop, not the current if block.

Hint: You only increment charcount IF counter === 1. counter === 0 until the first instance is found, and becomes 2 when the second instance is found. if (word[i] === character). You’ll be off by one character at the end, which you can adjust in yor return statement.

Click for the code for the for loop
for (let i = 0; i < word.length; i++){
      if (word[i] === character){
        counter++;
      }
      if (counter === 1) {
        charcount++;
      }
  }