Over a million developers have joined DZone.

Using JavaScript's "in" Operator To Simplify Redundant Logical ORs

·
Example of using the JavaScript "in" operator to reduce a series of logical ORs. Obviously this can be expanded, but the point is present.

The "in" operator construct (x in y -or- prop in object) checks to see if x is a property of y.

https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/in_Operator


if ( foo == "bar" || foo == "foobar" || foo == "foo" )
{
 //...
}
// can be written as
if ( foo in { bar:1, foobar:1, foo:1 } )
{
 //...
}
Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}