Reputation: 8375
Hey guys I'm having an issue with this statement in Internet Explorer, I was wondering if there is a saner way to do it?
var NEWVARIABLE = NEWVARIABLE || {};
NEWVARIABLE.Tools = NEWVARIABLE.Tools || {};
Its giving me the error that NEWVARIABLE
does not exist
Upvotes: 0
Views: 168
Reputation: 92274
You cannot use (or test) a variable that's not been defined. I originally thought that's what you were doing with the following statement
var NEWVARIABLE = NEWVARIABLE || {};
However, thanks to Fabrício, I realized that the var declaration gets hoisted (moved to the top of the script tag and is therefore already declared when it hits the statement.
The less confusing way to test if a variable is to use typeof === 'undefined'
to see if a variable exists
var NEWVARIABLE;
if (typeof NEWVARIABLE === 'undefined') {
NEWVARIABLE = {};
}
You can use the same style when checking for properties, you don't have to use typeof
test for properties, you are allowed to test them even if they aren't defined.
Upvotes: 3
Reputation: 147363
You've accepted an answer, but it contains a misleading statement:
You cannot use (or test) a variable that's not been defined. That's what you're doing
The variable is declared, so it isn't what you are doing.
In the OP, the code:
> var NEWVARIABLE = NEWVARIABLE || {};
> NEWVARIABLE.Tools = NEWVARIABLE.Tools || {};
contains no syntax errors, the only case where it will throw an error is if NEWVARIABLE already exists and has a Tools property that throws an error when attempting to access or assign to it (as may happen with certain host objects).
If NEWVARIABLE
has previously been assigned a native object or primitive value, it will not throw an error, though the result may not be what you expect.
Upvotes: 0