javascript - How to make sure a variable is an object -


i have been programming javascript little while now, , still not quite sure if being lazy or not. have lot of:

if( typeof( something) === 'undefined' ){   // .. } 

however, becomes verbose. example, doing:

var redirecturls = hotplate.get('hotcoreauth/redirecturls/success') || {}; 

that's because in following lines treating redirecturls object, although might not defined @ (the function might return undefined).

is there "best practice" cheatsheet? wrote above lazy? it's alternative cumbersome:

var redirecturls = hotplate.get('hotcoreauth/redirecturls/success'); if( typeof( redirecturls ) === 'undefined' ){   redirecturls = {} } 

i realise shortcut less robust, again, people either have set value, or not.

ideas?

merc.

when using "shortcut", equivalent following:

var redirecturls = hotplate.get('hotcoreauth/redirecturls/success'); if (!redirecturls) redirecturls = {}; 

the specification (ecma-262) states logical or operator (||) tests whether first expression (in case, function call) coerces true or not -- if coerces true, return first expression, else return second one.

it states coerces true , false (§9.2 - note isn't given verbatim):

false:

  • the numbers +0, -0, , nan
  • the empty string ("")
  • false
  • null
  • undefined

true: else (including stuff new boolean(false))

so, if don't mind letting numbers, strings or value true through, logical or "shortcut" ok. note "verbose" code might break if redirecturls null:

var redirecturls = null; if (typeof redirecturls === 'undefined') {   redirecturls = {}; } redirecturls.test = '1'; // typeerror: cannot set property 'test' of null 

Comments