Is there a simpler way to rewrite the following condition in JavaScript?
if ((x == 1) || (x == 3) || (x == 4) || (x == 17) || (x == 80)) {...}
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.
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.
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.
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.
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.
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