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:

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

{{ parent.tldr }}

{{ parent.urlSource.name }}