In my endeavour to write clean Javascript code as a beginner, I was recently reading this article about namespacing in JavaScript when I stumbled upon this paragraph:
The code at the very top of the next sample demonstrates the different ways in which you can check to see if a variable (object namespace) already exists before defining it. You'll commonly see developers using Option 1, however Options 3 and 5 may be considered more thorough and Option 4 is considered a good best-practice.
// This doesn't check for existence of 'myApplication' in // the global namespace. Bad practice as you can easily // clobber an existing variable/namespace with the same name var myApplication = {}; /* The following options *do* check for variable/namespace existence. If already defined, we use that instance, otherwise we assign a new object literal to myApplication. Option 1: var myApplication = myApplication || {}; Option 2 if(!MyApplication) MyApplication = {}; Option 3: var myApplication = myApplication = myApplication || {} Option 4: myApplication || (myApplication = {}); Option 5: var myApplication = myApplication === undefined ? {} : myApplication; */
Option 1 is certainly the one I have seen used most of the time, and I understand it well.
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?
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.
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.
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?
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?