Detecting an undefined object property
Share
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The usual way to check if the value of a property is the special value
undefined
, is:To check if an object does not actually have such a property, and will therefore return
undefined
by default when you try to access it:To check if the value associated with an identifier is the special value
undefined
, or if that identifier has not been declared:Note: this last method is the only way to refer to an undeclared identifier without an early error, which is different from having a value of
undefined
.In versions of JavaScript prior to ECMAScript 5, the property named “undefined” on the global object was writeable, and therefore a simple check
foo === undefined
might behave unexpectedly if it had accidentally been redefined. In modern JavaScript, the property is read-only.However, in modern JavaScript, “undefined” is not a keyword, and so variables inside functions can be named “undefined” and shadow the global property.
If you are worried about this (unlikely) edge case, you can use the void operator to get at the special
undefined
value itself: