JavaScript : The humble ‘in’ operator

 

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.

if ( "m" in obj ) obj["m"]() ;

2.

if ( "undefined" != typeof obj.m) obj.m() ;

3.

if (obj.m) obj.m() ;

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 :

if ( "undefined" !== typeof obj && "function" === typeof obj.m ) obj.m() ;

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

6 thoughts on “JavaScript : The humble ‘in’ operator”

Comments are closed.