What's the best way of checking if an object property in JavaScript is undefined?
Sorry, I initially said variable rather than object property. I believe the same == undefined
approach doesn't work there.
What's the best way of checking if an object property in JavaScript is undefined? Sorry, I initially said variable rather than object property. I believe the same |
||||
show 2 more comments |
Use:
|
|||||||||||||||||||||
|
I believe there are a number of incorrect answers to this topic. Contrary to common belief "undefined" is NOT a keyword in javascript, and can in fact have a value assigned to it.
Additionally, The most robust way to perform this test is:
This will always return the correct result, and even handles the situation where myVar is not declared. |
|||||||||||||||||||||
|
In JavaScript there is null and there is undefined. They have different meanings.
Marijn Haverbeke states, in his free, online book "Eloquent JavaScript" (emphasis mine):
So, I guess the best way to check if something was undefined would be:
Hope this helps! Edit: In response to your edit, object properties should work the same way.
|
|||||||||||||||||||||
|
This worked for me while the others didn't. |
|||||||||||||||||||||
|
The issue boils down to three cases:
This tells us something I consider important: There is a difference between an undefined member and a defined member with an undefined value. But unhappily
Its worth noting that these tests are the same for
I'd argue that in some cases it makes more sense (and is clearer) to check whether the property is there, than checking whether it is undefined, and the only case where this check will be different is case 2, the rare case of an actual entry in the object with an undefined value. For example: I've just been refactoring a bunch of code that had a bunch of checks whether an object had a given property.
Which was clearer when written without a check for undefined.
But as has been mentioned these are not exactly the same (but are more than good enough for my needs). |
|||||||||||||||||
|
I'm not sure where the origin of using
|
|||||||||||||||||||||
|
Ok. What does this mean: "undefined object property"? Actually it can mean two quite different things! First, it can mean the property that has been never defined in object and, second, it can mean the property that has undefined value. Let's see at this code:
Is
So we can clearly see that So what to do?1) You want to know if property is undefined by either first or second meaning (most typical situation).
2) You want to just know if object has some property and don't care of its value.
Notes:
Final fight:
|
|
You say lots of right things, but your statements about serverside js are unfounded and wrong. It doesn't need an (accessible) global object for global variables,
undefined does exist very well. And it doesn't need to have a window reference to the global object to have a global object at all. Actually, in Node.js you can access it via the global variable (and of course via this )
–
Bergi
Aug 28 '13 at 12:59
|
||
|
@Bergi thank you for your comment. I have corrected my answer. In my defense I can say that currently (as of v.0.10.18) official Node.js documentation says nothing about
undefined as a member of global . Also neither console.log(global); nor for (var key in global) { ... } doesn't show undefined as a member of global. But test like 'undefined' in global show the opposite.
–
Konstantin Smolyanin
Sep 11 '13 at 10:53
|
||
|
It didn't need extra documentation since it's in the EcmaScript spec, which also says that
[[Enumerable]] is false :-)
–
Bergi
Sep 11 '13 at 11:00
|
||
|
It's better to use the strict equality operator:
x == undefined also checks whether x is null, while strict equality does not (if that matters).(source) Or you can simply do this:
Here you check if there's any value that can make the variable look false (undefined, null, 0, false, ...). Not a good method for integers ('0' is not false), but might do well for object properties. |
|||||||||||||
|
I hate to add yet another answer to an old question, but many existing ones are misleading at best. Never use Of course, this potential already exists in the case of object properties, which appears to be the topic of this question. Let’s just ignore the
The “default value” of a property on an object is
This will check for the existence of the
This will check for the existence of the
This is the same as above, but will use the canonical
This one also checks for
This checks for the other falsy values (I hope that’s obvious) –
To sum up: don’t use If you are paranoid about
Still paranoid? Compare against |
|||||||||||||||||||||
|
Crossposting my answer from related question How to check for "undefined" in JavaScript? Specific to this question, see test cases with Some scenarios illustrating the results of the various answers: http://jsfiddle.net/drzaus/UVjM4/ (Note that the use of Code for reference:
And results:
|
|||
|
if you do:
It will fail when the var myvar does not exists because myvar is not defined, so the script is broken and the test has no effect. Because the window object has a global scope (default object) outside a function, a declaration will be 'attached' to the window object. for example:
the global var myvar is the same as window.myvar or window['myvar'] To avoid errors to test when a global variable exists, you better use:
The question if a var really exists doesn't matter, it's value is incorrect. Otherwise, it is silly to initialize variables with undefined, better use the value false to initialize. When you know that all variables that you declare are initialized with false, you can simply check it's type or rely on !window.myvar to check if it has a proper/valid value. So even when the variable is not defined then !window.myvar is the same for myvar=undefined or myvar=false or myvar=0. When you expect a specific type, test the type of the variable. To speed up testing a condition you better do:
When the first and simple condition is true, the interpreter skips next tests. It is always better to use the instance/object of the variable to check if it got a valid value. It is more stable, a better way of programming. Cheers! Kind regards, Erwin Haantjes |
||||
|
Returns false if variable is set, and true if is undefined. Then use:
|
|||||||||||||
|
I didn't see (hope I didn't miss it) anyone checking the object before the property. So, this is the shortest and most effective (though not necessarily the most clear):
If the obj or obj.prop is undefined, null, or "falsy", the if statement will not execute the code block. This is usually the desired behavior in most code block statements (in JavaScript). |
|||||
|
The solution is incorrect. In javascript,
will return true because they both are "casted" to a boolean and are false. The correct way would be to check
which is the identity operator... |
|||||||||
|
You can get array all undefined with path using following code.
jsFiddle link |
|||||
|
In this article I read that frameworks like Underscore use this function:
|
|||||
|
if (window.x) { } is error safeMost likely you want "if (window.x)". This check is safe even if x hasn't been declared (var x;) - browser doesn't throw an error. Example: I want to know if my browser supports History API
How this works:window is an object which holds all global variables as its members and it is legal to try to access a non-existing member. If x hasn't been declared or hasn't been set then window.x returns undefined. undefined leads to false when if() evaluates it. |
|||
|
Here is my situation: I am using the result of a REST call. The result should be parsed from JSON to a JavaScript object. There is one error I need to defend. If the args to the rest call were incorrect as far as the user specifying the args wrong, the rest call comes back basically empty. While using this post to help me defend against this, I tried this.
For my situation, if restResult.data[0] === "object", then I can safely start inspecting the rest of the members. If undefined then throw the error as above. What I am saying is that for my situation, all the suggestions above in this post did not work. I'm not saying I'm right and everyone is wrong. I am not a JavaScript master at all, but hopefully this will help someone. |
||||
|
Compare with
It's not as verbose as |
|||||
|
|
|||
|
Also same things can be written shorter:
or
|
|||
|
All the answers are incomplete. This is the right way of knowing that there is a property 'defined as undefined' :
Example:
Too bad that this been the right answer is buried in wrong answers >_< So, for anyone who pass by, I will give you undefineds for free!!
|
||||
|
This doesn't look up through the prototype chain, however. |
|||||
|
You can also make it into a function, as shown here:
|
|||||||||||||
|
Thank you for your interest in this question.
Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.
Would you like to answer one of these unanswered questions instead?
o.prop === undefined
is the way to go, ortypeof(o.prop) == 'undefined'
if there is a risk somebody might define a variable by the nameundefined
. There is a lot of confusion in the answers. Note thato.prop == undefined
will givetrue
ifo.prop
is defined with the valuenull
. – clacke Jul 30 '10 at 8:58typeof(o.prop) == 'undefined'
is still true. To distinguish this case, you need to check'prop' in o
. – Dave Feb 19 '12 at 9:34