What's the difference between the return values of these two expressions...
Expression 1: typeof foo['bar'] !== 'undefined'
Expression 2: 'bar' in foo
... assuming that these conditions are met:
foo
is an object,foo
does not contain any properties that have the value undefined
set explicitly.In a JavaScript program, the correct way to check if an object property is undefined is to use the typeof operator. If the value is not defined, typeof returns the 'undefined' string.
The typeof undefined is the string "undefined" — and undefined is a falsy value that is loosely equal to null but not to other falsy values.
foo is an object of some kind, which you must have declared before using it. bar is the name of a function that is a member of the foo object. A simple example, var foo = { bar: function () { alert("Hello, World!" ); } }; // This displays an alert with the text "Hello, World!" foo.bar();
typeof is generally always guaranteed to return a string for any operand it is supplied with. Even with undeclared identifiers, typeof will return "undefined" instead of throwing an error.
The first tests the value of bar
in foo
.
The second tests for the existence of the bar
property in foo
.
var foo = {bar:undefined};
typeof foo['bar'] !== 'undefined'; // false
'bar' in foo; // true
EDIT:
To add some clarification from the comments below, the issue OP is having is that accessing the domConfig
property of window.document
throws an Error.
This is an issue not related to the typeof
operator, but rather to a specific issue with Firefox.
The issue has been documented here as a bug (back in 2003).
A few notable comments from that report:
Zbigniew Braniecki [:gandalf] 2003-11-19 09:09:31 PST
then why it can be iterated with for-in ?
Boris Zbarsky (:bz) 2003-11-19 09:24:05 PST
Because it is defined as a property on the nsIDOM3Document interface. It's just one that throws if you try to access its getter. ...
Zbigniew Braniecki [:gandalf] 2003-11-19 09:33:53 PST
... So what kind of bug is it?
The goal is to remove not implemented method/property from interface or to implement it?!?
Boris Zbarsky (:bz) 2003-11-19 09:53:23 PST
The goal is to eventually implement this.
My reading of the spec suggests that they should be the same. The "in" operator semantics are defined in terms of making a call to the internal (conceptual) [[HasProperty]]
method, which itself is defined in terms of [[GetProperty]]
. When [[HasProperty]]
returns "undefined", then the "in" operator results in boolean false
; otherwise it's true
. Based on the definition of what [[GetProperty]]
is supposed to do, that means that an "undefined" result of a property access would have the same meaning.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With