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 }
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.
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.
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!
= 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.
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 }
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