Why is var x = x = x || {} more thorough than var x = x || {}?

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 than var x = x || {}?

It isn’t.

Option 2 is fine but seems to lack a var myApplication beforehand or a if(!window.myApplication) otherwise if myApplication is not in the global scope the condition if(!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, with myApplication in the global scope (due to the var 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:

  1. var myApplication creates the global if it doesn’t already exist, leaves it untouched if it does
  2. myApplication || {} is evaluated and takes either the value in myApplication (if it’s truthy) or {} (if not); let’s call that value1
  3. myApplication = value1 (the one in the middle) is performed, and the result is value1
  4. 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 if myApplication is not in the global scope.

Indeed.

Option 5 is excluding the false-y values other than undefined but is it a good idea? If myApplication is say an empty string, the rest of the code is likely to fail, isn’t it?

Yes.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)