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||{}
These are VERY different.
First, without checking for
typeof ... === 'undefined'
you will essentially rewrite any 'falsy' values. But that's trivial, there are more subtle nuances.This will assign value of some
x
(not necessary global, it may be a localx
orx
local to some outer function) to globalx
(window.x
). When that 'local' x will go out of scope, its value at the moment of assignment will still be stored inwindow.x
variable.This works with
window.x
only; even if we forget at the moment about falsy values, it still does not work the same as the first one (it doesn't even check for 'local'x
existence).And this one may go completely haywire when
this
is volatile (event handlers, timeout functions, to name a few), and will not be allowed within outer functions' body in 'use strict' mode.Here is how to avoid clobbering
console.log
specifically:In general, use a dispatch table if you want to avoid the default(||) or ternary(?:) operators:
References
ECMAScript 2015, Section 19.2.1: The Function Constructor
JavaScript character escape sequences
Character Model for the World Wide Web: String Matching and Searching
Archive of Interesting Code
If you use this construct:
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 thatx
will either be completely undefined or already defined as an object then sure, go ahead...