Robin van Dijk
Robin van Dijk

Reputation: 827

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

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

Answers (5)

Penny Liu
Penny Liu

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

PaperBirdMaster
PaperBirdMaster

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

Dhanu Gurung
Dhanu Gurung

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

Frédéric Hamidi
Frédéric Hamidi

Reputation: 263147

You can also use a plain string:

var checkVowel = function(input) {
    return "aeiou".indexOf(input) >= 0;
};

Upvotes: 2

elclanrs
elclanrs

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

Related Questions