Simply use this, no need to loop through anything:
var findVowel = function(letter) {
return "aeiou".indexOf(letter) != -1; // return if the letter is found in "aeiou"
};
Or, my personal favorite:
var findVowel = function(letter) {
return ~"aeiou".indexOf(letter);
};
.indexOf()
returns -1
if the parameter isn't found in the string, otherwise, it returns the parameter's position in the string (a int from 0
to string length - 1
).
So in the first sample, if the .indexOf()
returns -1
, the letter is not a vowel. If it returns any other value, it is. (Hence the != -1
).
The ~
is a bitwise NOT, inverting that output:
-1
becomes 0
--> a false-ish value.
X
(Where X is positive or 0) becomes -(X+1)
--> A true-ish value.
This way, the function will return true-ish if the letter is a vowel, and false-ish if it's not.
If you need a "strict" boolean output, replace the return
with this:
return !!~"aeiou".indexOf(letter);
The !!
is a double boolean NOT
(So, invert the boolean value twice), this casts the True-ish value to a true
, and a false-ish value (0
) to a false
.