0

Have to debug a certain segment of code for this class and I can't figure out why this JS counts all letters and not just vowels.

var text, i, sLength, myChar;
var count;
var text = prompt("Type a phrase please"); //put var in front of text and   fixed " in place of ' in front of type
count = 0;
for (i = 1; i <= text.length; i+= 1){
    myChar = text[i];
    if (myChar == 'a' || 'o' || 'e' || 'u'){ //switched to the proper vowels
        count += 1;
        console.log('Vowel:', myChar);   
    }
    console.log(myChar, count);
}
alert (count); //put the count in () instead of alert
joeygmurf
  • 27
  • 1
  • 5

3 Answers3

0

The line doing the comparison isn't doing the check properly. It should be:

if (myChar == 'a' || myChar == 'o' || myChar == 'e' || myChar == 'u')
MWS
  • 78
  • 3
  • 10
0

The correct JS would be this.

var text, i, sLength, myChar;
var count;
var text = prompt("Type a phrase please"); //put var in front of text and   fixed " in place of ' in front of type
count = 0;
for (i = 1; i <= text.length; i+= 1){
    myChar = text[i];
    if (myChar == 'a' || myChar == 'o' || myChar =='e' || myChar == 'u'){ //switched to the proper vowels
        count += 1;
        console.log('Vowel:', myChar);   
    }
    console.log(myChar, count);
}
alert (count)

The reason yours doesn't work is because it is asking whether 'o' is true when you say expression || 'o' and since a string literal is not a falsy value (0, "", null, undefined, false) it is staying true for every iteration of the loop.

John
  • 7,114
  • 2
  • 37
  • 57
0

Super Short Way

function countVowels (string) {
    return string.match(/a|e|i|o|u/g).length;
}

Use as:

alert(countVowels(prompt("Type a phrase please")));


You're if is an invalid condition. If you wish to quickly check if a value is one of some options, try the following:
if (['a', 'e', 'i', 'o', 'u'].indexOf(myChar) > -1) {
}


Function!

function hasOptions (c) {
    return arguments.splice(1).indexOf(c);
}

Then

if (hasOptions(myChar, 'a', 'e', 'i', 'o', 'u'))
Downgoat
  • 13,771
  • 5
  • 46
  • 69