Search code examples
javascriptglobal-variablesvariable-assignmentlocal-variablesnot-exists

shortcut to existentially define variable in javascript


To avoid clobbering existing variables, I have code like this

window.x = typeof x != "undefined" ? x : {}

Which seems like a very long winded way to define something, but necessary to avoid console errors.

I tried this out instead, and it seems to work ok. Is it ok to define a variable like this?

window.x=window.x||{}

Or even in the global scope...

x=this.x||{}

Solution

  • If you use this construct:

    window.x=window.x||{}
    

    And x is defined but has a falsy value (zero, the empty string, null, NaN, undefined, and of course false) then that value will be overwritten with a new empty object. If that is acceptable to you because you are confident that x will either be completely undefined or already defined as an object then sure, go ahead...