2

Is

if(!!object)
{
 // do something if object found
}

a much more guarenteed way to see if any object is present?

if(object)
{

}
unj2
  • 52,135
  • 87
  • 247
  • 375
  • possible duplicate of [How can I check whether a variable is defined in JavaScript?](http://stackoverflow.com/questions/519145/how-can-i-check-whether-a-variable-is-defined-in-javascript) – Felix Kling May 24 '12 at 14:14

3 Answers3

7

the safest way to check that something is defined:

if (typeof thingy !== 'undefined')
jbabey
  • 45,965
  • 12
  • 71
  • 94
  • 1
    why wouldn't !thingy catch this case? – unj2 May 24 '12 at 14:20
  • @kunj2aan Consider the different outcome when dealing with a variable containing the value `false` or any falsy value. If you can make some assumption about your variable then other methods are fine. For instance, the result of `getElementById` will often just use `if(result)` because you know it will never return false or 0. – James Montagne May 24 '12 at 14:35
  • @kunj2aan `!thingy` will throw an exception if thingy has not been defined. – jbabey May 24 '12 at 14:49
1
if(typeof my_var == 'object'){

}
Rycicle
  • 11
  • 2
1

There are so many ways to check that...

if ( object )
if ( !!object )
if ( object !== undefined )
if ( typeof object !== 'undefined' )
if ( object !== void 0 )
if ( {}.toString.apply( object ).subtr( 0, 7 ) === '[object' )

Etc.

Florian Margaine
  • 58,730
  • 15
  • 91
  • 116