user1324518
user1324518

Reputation: 11

Setting up a if else function that detects if it is a vowel

I am new to JavaScript and I know I did something wrong because I keep getting true as a result. Can someone please point out my mistake? Thanks in advance.

function checkForVowel(x){
   if(x == "a", "e", "i", "o", "u"){
       document.write("true");
   }else{
       document.write("false");
   }
}

checkForVowel("n");

Upvotes: 0

Views: 2028

Answers (3)

Derek 朕會功夫
Derek 朕會功夫

Reputation: 94319

I don't know why, but no one suggested this. :/

function checkForVowel(x){
    document.write(/[aeiou]/i.test(x));   //Clearly this is even simpler than
}                                         // other methods.

Or

function checkForVowel(x){
   if(x.search(/[aeiou]/i) != -1){
       document.write("true");
   }else{
       document.write("false");
   }
}

Upvotes: 1

jfriend00
jfriend00

Reputation: 707328

Sometimes the code is a lot cleaner to test against a data structure than use lots of if/else code. Which is faster may depend upon the specific browser engine and how many comparisons you have. This one looks to see if the string is present in a string of vowels:

var vowels = "aeiou";

function checkForVowel(x) {
    return(vowels.indexOf(x.toLowerCase()) >= 0);
}

This one tests to see if the test char is in a javascript object which isn't needed here, but is another interesting way to test if something is in a set:

var vowels = {a: true, e: true, i: true, o: true, u: true};

function checkForVowel(x) {
    return(x.toLowerCase() in vowels);
}

Upvotes: 2

Ry-
Ry-

Reputation: 224913

JavaScript's comparison operator isn't magic; you'll need to do each comparison separately. You can check for "any of these" using a logical OR, ||:

if(x == "a" || x == "e" || x == "i" || x == "o" || x == "u")

Or, since you have many single-character strings, you can make use of indexOf. But the above might be easier to understand if you're just starting out.

if(x.length === 1 && 'aeiou'.indexOf(x) > -1)

As for the reason you keep getting true, it's that , is actually an operator in JavaScript, mainly invented to confuse people1. It evaluates its left side, then evaluates its right side, and returns the right side. So your expression boils down like this:

if(x == "a", "e", "i", "o", "u")
if("e", "i", "o", "u")
if("i", "o", "u")
if("o", "u")
if("u")

Which is a truthy value.

1 Not actually.

Upvotes: 11

Related Questions