Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: The prettiest way to compare one value against multiple values [duplicate]

Whats the prettiest way to compare one value against multiples options?

I know there are loads of ways of doing this, but I'm looking for the neatest.

i ask because i'd hoped this was workable (it isn't, quite obviously when you look at it):

if (foobar == (foo||bar) ) {      //do something } 
like image 749
thelastshadow Avatar asked Feb 02 '12 23:02

thelastshadow


People also ask

How to compare multiple values in js?

To check if a variable is equal to all of multiple values, use the logical AND (&&) operator to chain multiple equality comparisons. If all comparisons return true , all values are equal to the variable.

Why we use === in JavaScript?

The === operator compares operands and returns true if both operands are of same data type and have some value, otherwise, it returns false. The !== operator compares operands and returns true if both operands are of different data types or are of the same data type but have different values.

How do I compare 3 numbers in JavaScript?

To compare 3 values, use the logical AND (&&) operator to chain multiple conditions. When using the logical AND (&&) operator, all conditions have to return a truthy value for the if block to run. Copied!

How do you compare variables in JavaScript?

= is used for assigning values to a variable in JavaScript. == is used for comparison between two variables irrespective of the datatype of variable. === is used for comparision between two variables but this will check strict type, which means it will check datatype and compare two values.


1 Answers

Don't try to be too sneaky, especially when it needlessly affects performance. If you really have a whole heap of comparisons to do, just format it nicely.

if (foobar === foo ||     foobar === bar ||     foobar === baz ||     foobar === pew) {      //do something } 
like image 69
david Avatar answered Sep 24 '22 07:09

david