unj2
unj2

Reputation: 53481

Better way to see if an object is present in JavaScript

Is

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

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

if(object)
{

}

Upvotes: 2

Views: 2300

Answers (3)

Florian Margaine
Florian Margaine

Reputation: 60717

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.

Upvotes: 1

Rycicle
Rycicle

Reputation: 11

if(typeof my_var == 'object'){

}

Upvotes: 1

jbabey
jbabey

Reputation: 46647

the safest way to check that something is defined:

if (typeof thingy !== 'undefined')

Upvotes: 7

Related Questions