Reputation: 19
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
Reputation: 1
Two main issues:
You need to finish your iteration through the string letters before returning the total count. Currently, the return counter;
is inside the for-loop.
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
Reputation: 456
Couple of things.
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