Reputation: 827
I just started learning JavaScript a few days ago and I am wondering:
var input = prompt();
var checkVowel = function (input) {
if (input === "a" || input === "e" || input === "i" || input === "o" || input === "u") {
return true;
} else {
return false;
}
}
checkVowel(input);
Isn't there a shorter way to write the multiple inputs instead of input === "e"
each time?
Upvotes: 5
Views: 2811
Reputation: 17498
This is the shortest I got. You can also use Array.prototype.includes() to reduce multiple OR conditions.
const isVowel = input => ['a', 'e', 'i', 'o', 'u'].includes(input);
Upvotes: 1
Reputation: 13298
Isn't there a shorter way to write the multiple inputs instead of input === "e" each time?
If you want to check multiple inputs, there's no shorter way to do it other than to check every input (but there are better methods to do it, if you check all the other answers).
I'll advice you to read about the switch
statement:
var checkVowel = function(input){
switch (input) {
case "a":
case "e":
case "i":
case "o":
case "u":
return true;
default:
return false;
}
}
The switch allows you to check multiple inputs in a readable way. This approach isn't shorter at all but is way more readable.
Upvotes: 1
Reputation: 8858
I generally use this pattern for such a scenario:
var checkVowel = function(input) {
if (['a', 'e', 'i', 'o', 'u'].indexOf(input) !== -1) {
return true;
} else {
return false;
}
}
Upvotes: 1
Reputation: 263147
You can also use a plain string:
var checkVowel = function(input) {
return "aeiou".indexOf(input) >= 0;
};
Upvotes: 2
Reputation: 94131
You can do this with regex:
var checkVowel = function(input) {
return /^[aeiou]$/.test(input);
};
Or using indexOf
with an array:
var checkVowel = function(input) {
return ['a','e','i','o','u'].indexOf(input) > -1;
};
Upvotes: 7