Here i am just creating a global namespace for my application and everything works as expected
var MYAPP = MYAPP || {} ;
but if I omit var keyword ( i know it’s not the right way), javascript throw an error “ReferenceError: MYAPP2 is not defined” .
MYAPP2 = MYAPP2 || {};
just out of curiosity can some one explain me in second case why javascript is not able to resolve the reference.
The first version doesn’t produce an error because Javascript’s variable hoisting makes it equivalent to this:
Importantly, the declaration part of this does not overwrite any existing declaration or assignment that was already made to the variable.
This is what allows this pattern to be used repeatedly within a single scope.
MYAPPeither retains the value it already had, or is initialised to an empty object.in the second case, that declaration step is effectively omitted. If the variable has not already been declared (or otherwise exists in scope, i.e. as a property of the global object) then the error you see is generated.