Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorter way to write multiple "or"-conditions in if-statement

Tags:

javascript

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?

like image 876
Robin van Dijk Avatar asked Mar 27 '14 11:03

Robin van Dijk


Video Answer


5 Answers

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;
};
like image 159
elclanrs Avatar answered Oct 21 '22 03:10

elclanrs


You can also use a plain string:

var checkVowel = function(input) {
    return "aeiou".indexOf(input) >= 0;
};
like image 42
Frédéric Hamidi Avatar answered Oct 21 '22 03:10

Frédéric Hamidi


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;
  }    
}
like image 33
brg Avatar answered Oct 21 '22 04:10

brg


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.

like image 1
PaperBirdMaster Avatar answered Oct 21 '22 04:10

PaperBirdMaster


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);
like image 1
Penny Liu Avatar answered Oct 21 '22 02:10

Penny Liu