hotpocket
hotpocket

Reputation: 19

For loop to count the number of vowels in a string (javascript)

I'm writing a function that will count the number of vowels in a string. I decided to use a for-loop and an if-statement to do this.

function vowels (string) {
    var counter = 0;
    for (let i=0; i < string.length; i++) {
        if (i == 'a' || i == 'e' || i == 'i' || i == 'o' || i == 'u') {
            counter++;
        }return counter;
    } 
}

This is my code. When I call the function, it only returns 0 no matter how many vowels my string has. What's wrong?

Upvotes: 1

Views: 2130

Answers (2)

ektefaie
ektefaie

Reputation: 1

Two main issues:

  1. You need to finish your iteration through the string letters before returning the total count. Currently, the return counter; is inside the for-loop.

  2. You also need to compare a letter string[i] with a vowel during each iteration. i will compare a number to a vowel not a letter.

     function vowels(string) {
         var counter = 0;
         for (let i=0; i < string.length; i++) {
             if (string[i] == 'a' || string[i] == 'e' || string[i] == 'i' || string[i] == 'o' || string[i] == 'u') {
                 counter++;
             }
         }
         return counter;
     }
    

Upvotes: 0

Morilon
Morilon

Reputation: 456

Couple of things.

  1. You're not looping through the string but the length of it. You need to use the length to get the position of the string.
  2. You're returning the counter, exiting the function, on index 0.

I also added a toLowerCase to account for casing. A === a but that depends on your use case.

Always use === operator when validating types. You can learn more here but basically == compares value only and === compares value and type.

e.g. 0 == '0' equals true and 0 === '0' equals false

function vowels (value) {
    let counter = 0;
    let char = '';
    for (let i = 0; i < value.length; i++) {
        char = value[i].toLowerCase();
        if (char === 'a' || char === 'e' || char === 'i' || char === 'o' || char === 'u') {
            counter++
        }
        
    } 
    return counter;
}

vowels("AaBbCcDdEe");

returns 4. AaEe.

Upvotes: 2

Related Questions