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?
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;
};
You can also use a plain string:
var checkVowel = function(input) {
return "aeiou".indexOf(input) >= 0;
};
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;
}
}
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With