Wednesday, October 28, 2009

Using the "in" operator in conditionals

Most of us are familiar with the for..in loop construct:

for (var i in object) {
   /* some iterative action here */
}

Less well-known is the use of "in" as an operator to test if a named property exists on an object:

>>> var x = {foo:1, bar:2, baz:'cat'};

>>> ('foo' in x)
true

>>> ('bar' in x)
true

>>> ('qux' in x)
false
This works on methods, too:
>>> ('toString' in x)
true

It's particularly neato for testing the existence of properties with values that could be interpreted as false:

>>> var x = {foo:null, bar:false, baz:0};

>>> (x.foo)
null

>>> ('foo' in x);
true

>>> (x.bar)
false

>>> ('bar' in x)
true

5 Comments:

At 9:43 AM, Anonymous Anonymous said...

Wow, that's great. Thanks for documenting this.

 
At 1:26 AM, Blogger Unknown said...

Watch out for testing the non-existing of properties.

E.g.

>>var o = {};
>>(!"a" in o)
false

Why? Because the ! operator takes precedence, so it evaluates to

>>(false in o)
false

Hence you must do

>>(!("a" in o))
true

 
At 8:34 PM, Blogger Nordin said...

Thanks.. never heard about this before. Next question.. Is this supported by all browsers?

 
At 3:27 PM, Blogger Unknown said...

I have tested in all 5 main browsers (IE,Chrome,Opera,Safari,Firefox) with the same results. I am fairly sure that this point flows from the ECMAScript specification itself and the operator precedence rules. Just an easy one to overlook (for me at least)!

 
At 6:46 AM, Blogger Unknown said...

I think you should probably be using
>> a.hasOwnProperty('foo')
instead of
>> ('foo' in a)

The 'in' also returns True for inherited properties which might not be what you want.

 

Post a Comment

<< Home