What's the best way of checking if an object property in JavaScript is undefined?
Join them; it only takes a minute:
Use:
If an object variable which have some properties you can use same thing like this:
|
|||||||||||||||||||||
|
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 |
|||||||||||||||||||||
|
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.
|
|||||||||||||||||||||
|
What does this mean: "undefined object property"? Actually it can mean two quite different things! First, it can mean the property that has never been defined in the object and, second, it can mean the property that has an undefined value. Let's look at this code:
Is
We can clearly see that So what to do?1) You want to know if a property is undefined by either the first or second meaning (the most typical situation).
2) You want to just know if object has some property and don't care about its value.
Notes:
Final fight:
|
|
@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
|
||
|
Regarding
Minuses of typeof obj.prop == 'undefined' , this can be avoided by writing as typeof obj.prop == typeof undefined . This also gives a very nice symmetry.
– hlovdal
Oct 24 '14 at 11:01
|
Many of the existing answers 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 |
|||||||||||||||||||||
|
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). |
|||||||||||||||||||||
|
This worked for me while the others didn't. |
|||||||||||||||||||||
|
I'm not sure where the origin of using
|
|||||||||||||||||||||
|
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 variable 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 variable 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 variable really exists doesn't matter, its value is incorrect. Otherwise, it is silly to initialize variables with undefined, and it is better use the value false to initialize. When you know that all variables that you declare are initialized with false, you can simply check its type or rely on 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 the 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 and is a better way of programming. (y) |
||||
|
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). |
|||||||||
|
In the article Exploring the Abyss of Null and Undefined in JavaScript I read that frameworks like Underscore.js use this function:
|
|||||||||||||
|
'if (window.x) { }' is error safeMost likely you want 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 |
|||||
|
Reading through this, I'm amazed I didn't see this. I have found multiple algorithms that would work for this. Never DefinedIf the value of an object was never defined, this will prevent from returning
Defined as undefined Or never DefinedIf you want it to result as
Defined as a falsy value, undefined,null, or never defined.Commonly, people have asked me for an algorithm to figure out if a value is either falsy,
|
|||||
|
You can get an array all undefined with path using the following code.
jsFiddle link |
|||||
|
Returns false if variable is set, and true if is undefined. Then use:
|
|||||
|
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 |
|||||||||
|
|
|||
|
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!!
|
||||
|
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... |
|||||||||
|
Going through the comments, for those who want to check both is it undefined or its value is null:
If you are using jQuery Library then
|
|||||
|
If you are using Angular:
Underscore.js:
|
|||||
|
Also same things can be written shorter:
or
|
|||||
|
I would like to show you something I'm using in order to protect the
This forbids anyone to change the |
||||
|
From lodash.js.
It creates an variable named |
|||
|
Use: To check if property is undefined:
To check if property is not undefined:
|
||||
|
There is a nice way to assign a defined property to a new variable if it is defined and assign a default value to it if undefined.
It's suitable if you have a function, which receives an additional config property:
Now executing
|
||||
|
I use
It first detects that variable |
|||
|
This doesn't look up through the prototype chain, however. |
|||||
|
protected by Starx Apr 25 '12 at 8:45
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
typeof(o.prop) == 'undefined'
is still true. To distinguish this case, you need to check'prop' in o
. – djd Feb 19 '12 at 9:34o.prop !== undefined
ortypeof(o.prop) != 'undefined'
– Sliq Jul 17 '13 at 9:21