Search code examples
javascriptfor-loopwhile-loop

Trouble Turning a For Loop Into a While Loop


I'm supposed to turn the following function into a while loop. The function is supposed to count all the e's that appear in a certain string. Here's the function using a for loop:

function eCounter(word) {
  let count = 0;

  for (let index = 0; index < word.length; index++) {
    let char = word[index];
    if (char === "e" || char === "E") {
      count += 1;
    }
  }

  return count;
};

Here's my code:

function eCounter(word) {
  let count = 0
  let index = 0;
  let char = word[index];
  
while (char === "e" || char === "E") {
index+= count;
}
return count;
}
};

console.log(eCounter("apple")); // => 1
console.log(eCounter("appleapple")); // => 2
console.log(eCounter("Appleee")); // => 3

If count and index are both 0, and char is defined, I'm not sure what to do next. When I console.log the strings, all three return zero.

Any help I can get will be greatly appreciated.

I tried putting all of the code from the for loop into a while loop. I figured if I rearranged the for loop code into a while loop, it would return the number of e's in each string. But when I run the code, all three counts return 0.


Solution

  • It's similar to for loop

    function eCounter(word) {
      let count = 0
      let index = 0;
      while (index < word.length) {
        const char = word[index]
        if (char === "e" || char === "E") {
          count++
        }
        index++
      }
      return count;
    }