JavaScript object detection
-
22-06-2021 - |
Question
I am currently practicing javascript and I'm currently having trouble with object detection. I want to create an object and detect whether it exists. Below is some example code I am currently using.
The code sample below is how I am creating my object.
var obj = obj || {};
Should I be using this?
if (typeof obj !== "undefined") {
// code
}
Or this?
if (obj !== null) {
}
Solution
The value undefined
means that the variable has not been assigned a value. The value null
indicates that it has been assigned the value null
. The ===
operator (and its negation, !==
) prevent type coercion.
Which is right? It all depends on what you are trying to accomplish. Both undefined
and null
are "falsy" values, meaning that each one evaluates to false
in a boolean context (as do false
, 0
, and the empty string).
Note that if obj
is null
, then typeof obj
is not "undefined"
.
OTHER TIPS
The usual practice is to use:
var obj = obj || {};
When that code runs, you can be certain that obj
has been defined (because of the var
declaration), though it may not have been assigned a value.
If the value of obj
resolves to a "falsey" value, then you will assign a reference to a new object.
Possible outcomes are:
If
obj
has not been assigned a value, a new object reference is assigned.If
obj
has previously been assigned a "falsey" value, it will be replaced by a new object reference (which may mess with whatever code assigned it the falsey value).If
obj
has previously been assigned a "truethy" primitive value, the following assignments of properties toobj
will throw an error and script execution will stop.if
obj
is already a reference to an object other thannull
, then subsequent assignments of properties will be to that object. Depending on the type of object, things may be ok. Or not. Presumably something outside your control created the object and so may modify or destroy it without your knowledge. What will you do?
It is not possible in javascript to deal, in general, with cases 2 and 3, or 4 where it's not your obj
you're dealiing with. So use a name that is unlikely to clash with any other and hope you get #1 or #4 and things go well.
Incidentally, code added after yours may still result (more or less) in #4, even if you had #1 at the point the code is executed.
There is no additional benefit to tests like:
if (typeof obj == 'undefined')
because the outcome is essentially the same.