If the article claims Option 3 is “more thorough,” it’s incorrect. There’s no point to the middle of that assignment chain at all.
Would someone be able to shed some light on the differences between the different options and in particular explain why option 3 is described as more thorough?
First, a caveat: Here in 2018, you probably don’t want to use any of these. Instead, use proper modules, either via one of the various module definition syntaxes (AMD, CommonJS, RequireJS) with a relevant tool, or via ES2015+ modules with import
and export
(and probably a relevant tool such as Babel and perhaps Webpack or Browserify, although current versions of Chrome, Safari, and Edge support modules natively, and Firefox does as well currently behind a flag).
Why is
var x = x = x || {}
more thorough thanvar x = x || {}
?
It isn’t.
Option 2 is fine but seems to lack a
var myApplication
beforehand or aif(!window.myApplication)
otherwise ifmyApplication
is not in the global scope the conditionif(!myApplication)
would throw an error, wouldn’t it?
Yes. (Assuming that production occurs at global scope. if it’s not at a global scope and there’s an in-scope myApplication
anywhere in the current scope chain, it won’t throw because myApplication
won’t be an unresolved symbol.)
Option 3 is the one I have trouble with: my understanding is that the
myApplication = myApplication
is executed first, withmyApplication
in the global scope (due to thevar
at the begining). My problem is that I can’t think of a case where this option does anything more than option 1.
No, if you have
var myApplication = myApplication = myApplication || {}
this is the order in which things happen:
var myApplication
creates the global if it doesn’t already exist, leaves it untouched if it doesmyApplication || {}
is evaluated and takes either the value inmyApplication
(if it’s truthy) or{}
(if not); let’s call thatvalue1
myApplication = value1
(the one in the middle) is performed, and the result isvalue1
myApplication = value1
(the one on the left) is performed again for no good reason
Option 4 in my eyes would have been better written
window.myApplication || (myApplication = {})
to avoid throwing an error ifmyApplication
is not in the global scope.
Indeed.
Option 5 is excluding the false-y values other than
undefined
but is it a good idea? IfmyApplication
is say an empty string, the rest of the code is likely to fail, isn’t it?
Yes.