Reputation: 12132
function isVowel(char){
if(typeof char == 'string' && char.length > 1){
console.log('not a char');
return 'not a char';
} else {
if (char.toLowerCase() === ('a'||'e'||'i'||'o'||'u')){
console.log(char, true);
return true;
} else {
console.log(char, false);
return false;
}
}
}
document.writeln(isVowel('a'));
document.writeln(isVowel('e'));
document.writeln(isVowel('l'));
the result is: true, false, false;
it should be: true, true, false;
Can anyone help me why this is happening?
I'm just barely learning JavaScript...
Also, is there any way to refactor this code? I don't want to be repeating myself for every new condition..
Upvotes: 1
Views: 173
Reputation: 26228
The problem is here
if (char.toLowerCase() === ('a'||'e'||'i'||'o'||'u'))
Equality operators don't "distribute", you'll have to test the input against each possibility independently. A concise solution might be
if ("aeiou".indexOf(char.toLowerCase()) + 1) {
console.log(char, true);
return true;
}
Upvotes: 2
Reputation: 20490
('a'||'e'||'i'||'o'||'u')
is equal to "a"
To confirm the above, just try it using the console, or:
console.log(('a'||'e'||'i'||'o'||'u'));
My suggestion:
' aeiou'.indexOf(char) > 0
Complete version:
function isVowel(char){
if(typeof char == 'string' && char.length > 1){
console.log('not a char');
return 'not a char';
} else {
if (' aeiou'.indexOf(char) > 0){
console.log(char, true);
return true;
} else {
console.log(char, false);
return false;
}
}
}
document.writeln(isVowel('a'));
document.writeln(isVowel('e'));
document.writeln(isVowel('l'));
Refactored version:
function isVowel(char)
{
return ((typeof char == 'string') && (char.length == 1) && ('aeiou'.indexOf(char.toLowerCase()) != -1));
}
Upvotes: 3
Reputation: 9055
if (/[aeiou]/.test(char.toLowerCase())){
// ...
} else {
// ...
}
Upvotes: 3
Reputation: 28618
You need to separate ||
s like this:
char.toLowerCase() === 'a'
|| char.toLowerCase() === 'e'
|| char.toLowerCase() === 'i'
|| char.toLowerCase() === 'o'
|| char.toLowerCase() === 'u'
instead of like this:
char.toLowerCase() === ('a'||'e'||'i'||'o'||'u')
Here's a jsFiddle of the above:
Upvotes: 4