Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inconsistent behavior in JavaScript's conditional checking

Tags:

javascript

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?

like image 556
Buu Nguyen Avatar asked Nov 30 '10 11:11

Buu Nguyen


2 Answers

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.

like image 134
Matt Avatar answered Oct 02 '22 22:10

Matt


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.

like image 22
Alexandr Avatar answered Oct 02 '22 21:10

Alexandr