I want to build an object obj1
with property obj2
, which is another object. To avoid redeclaring obj1
and obj2
, I use the following code:
if (!obj1) obj1 = {};
if (!obj1.obj2) obj1.obj2 = {};
// code to use obj1
Assume, obj1
and obj1.obj2
aren't defined yet, the code causes the browser to report the error "obj1 is not defined".
If I change the code to:
if (typeof obj1==='undefined') obj1 = {};
if (!obj1.obj2) obj1.obj2 = {};
// code to use obj1
Then there's no error, while I think it should report "obj2 is not defined". I'm puzzled as to why the JavaScript treats the short-hand falsy check of a reference and a property differently. Can anyone shed a light on that?
If you would do:
if (!window.obj1) window.obj1 = {};
if (!obj1.obj2) obj1.obj2 = {};
You will find the code works as you expect.
obj1
isn't even a reference when you check it's existance; it's nothing. It doesn't exist because you haven't declared it (neither have you initialized it).
var obj1;
if (!obj1) obj1 = {};
if (!obj1.obj2) obj1.obj2 = {};
This will also work because you've declared the existance of obj1
; you just haven't initialized it.
All properties of an object that haven't been set hold the value undefined
; which is why it responds to your short hand !obj1.obj2
var obj1 = {};
obj1.a === undefined // true;
Variables however, must be defined before you can access them.
The "obj1" reference is not declared at all, as a result you get an error.
Use the following syntax for such kind of check:
var obj1 = obj1 || {};
By the way:
if (typeof obj1==='undefined') obj1 = {};
does not help if obj1 == null.
Don't declare global variables (without var). And I strongly recommend you to read the JavaScript: The Definitive Guide, 5th Edition. You may skip some chapters but pay your attention to Chapters 3, 7, 8, 9. They must be read and understood.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With