The humble ‘in’ operator

pro_js

This might be an “opportunity for optimization” … if not already discovered by someone else that is. First published on: Jul 19, 2009.

Consider the code bellow. Which one you prefer and why :
1.

[sourcecode language=”javascript”]if ( "m" in obj ) obj"m" ;[/sourcecode]

2.

[sourcecode language=”javascript”]if ( "undefined" != typeof obj.m) obj.m() ;[/sourcecode]

3.

[sourcecode language=”javascript”]if ( obj.m) obj.m() ;[/sourcecode]

3 seemed as an obvious winner, but then I gave it some thought, and
…. I still have no easy answer to this one … 1 or 3 ?

Update 2010-02-11

Well, now, and after all the useful comments bellow, it seems to me the “best” solution might be this :

[sourcecode language=”javascript”]
if ( "undefined" !== typeof obj && "function" === typeof obj.m ) obj.m() ;
[/sourcecode]

Of course now we have to decide what we do in the else part, of the above if() :)

6 thoughts on “The humble ‘in’ operator”

Comments are closed.