Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reduce multiple ORs in IF statement in JavaScript

Tags:

javascript

Is there a simpler way to rewrite the following condition in JavaScript?

if ((x == 1) || (x == 3) || (x == 4) || (x == 17) || (x == 80)) {...}
like image 798
Misha Moroshko Avatar asked Apr 13 '10 14:04

Misha Moroshko


People also ask

How do you handle multiple if conditions in JavaScript?

You can use the logical AND (&&) and logical OR (||) operators to specify multiple conditions in an if statement. When using logical AND (&&), all conditions have to be met for the if block to run.

How do you shorten if else statements in JavaScript?

Use the ternary operator to use a shorthand for an if else statement. The ternary operator starts with a condition that is followed by a question mark ? , then a value to return if the condition is truthy, a colon : , and a value to return if the condition is falsy.

Can we use multiple IF condition in JavaScript?

if else statements will execute a block of code when the condition in the if statement is truthy . If the condition is falsy , then the else block will be executed. There will be times where you want to test multiple conditions and you can use an if...else if...else statement.

How do you check multiple conditions in a single IF statement?

Here we'll study how can we check multiple conditions in a single if statement. This can be done by using 'and' or 'or' or BOTH in a single statement. and comparison = for this to work normally both conditions provided with should be true. If the first condition falls false, the compiler doesn't check the second one.


1 Answers

You could use an array of valid values and test it with indexOf:

if ([1, 3, 4, 17, 80].indexOf(x) != -1)

Edit    Note that indexOf was just added in ECMAScript 5 and thus is not implemented in every browser. But you can use the following code to add it if missing:

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length >>> 0;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

Or, if you’re already using a JavaScript framework, you can also use its implementation of that method.

like image 86
Gumbo Avatar answered Oct 08 '22 18:10

Gumbo