Sing OR || for an if statment

Hi,

Just wondering why…

function noOfVowels (string){

let vowels = 0;
for (let i = 0; i < string.length; i++){
    if (string[i] === "a" ){
        vowels++
    } 
    
}
return vowels;   

}

console.log(noOfVowels(“hello how are you today”));

This will return 2.

However

function noOfVowels (string){

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

}

console.log(noOfVowels(“hello how are you today”));

this just returns 23, all characters in the string :frowning:

Why is the || not recognised, and what is the the work around, please.

Thank you!

This is the wrong way to use ||. The || operator separates fully independent logical tests. "e" is not a full logical test, it’s just a single character, so it is truthy.

1 Like

To add onto what Jeremy said, non-empty strings are considered truthy. They are equal to the the boolean value true when tested.

MDN Article

if ("e") // true
if ("") // false

In your case, the following statement:

(string[i] === "a"||"e"||"i"||"o"||"u" )

Is asking if the letter is equal to the string "a". If it is not, then it tests if "e" is true. Since just testing a non-empty string by itself is true, this statement will always return true.

Repeat the way you compared the letter a for the rest of the letters.

1 Like

ahh, OK.

so it would have to be string[i] === “a” || string[i] === “e” || string[i] === “i” etc.

Thanks :slight_smile:

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.