Typeof foo ['bar']! == 'undefined' versus "bar" in foo

What is 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
  • foodoes not contain any properties for which the value is undefinedset explicitly.
+5
source share
6 answers

The first checks the value barin foo.

The second test for the existence of property barc foo.

var foo = {bar:undefined};

typeof foo['bar'] !== 'undefined'; // false

'bar' in foo;  // true

EDIT:

To add some clarification from the comments below, the OP problem is that accessing the property domConfig window.documentis causing an error.

, typeof, Firefox.

( 2003 ).

:

Zbigniew Braniecki [: gandalf] 2003-11-19 09:09:31 PST

in-in?

(: bz) 2003-11-19 09:24:05 PST

nsIDOM3Document. , , ....

Zbigniew Braniecki [: gandalf] 2003-11-19 09:33:53 PST

... ?

, / ?!?

(: bz) 2003-11-19 09:53:23 PST

, .

+5

, . "in" () [[HasProperty]], [[GetProperty]]. [[HasProperty]] "undefined", "in" false; true. , [[GetProperty]], , "undefined" .

+2
var foo = {};
foo.bar = undefined;

console.log("bar" in foo); // true
console.log(typeof foo["bar"] !== "undefined"); // false

var Con = function() {};
Con.prototype.bar = undefined;
var foo = new Con;

console.log("bar" in foo); // true
console.log(typeof foo["bar"] !== "undefined"); // false

in , for in true, key for in.

[] , " undefined".

var foo = {}
Object.defineProperty(foo, "bar", { 
    "value": 42,
    "enumerable": false

});

console.log("bar" in foo); // true (in chrome & FF4)
console.log(typeof foo["bar"] !== 'undefined'); // true

, in , . , .

var foo = {}
Object.defineProperty(foo, "bar", { 
    "value": 42,
    "writable": false

});

console.log("bar" in foo); // true (in chrome & FF4)
console.log(typeof foo["bar"] !== 'undefined'); // true

- , "readonly"

var foz = {}
Object.defineProperty(foz, "bar", { 
    "value": 42
});
var foo = Object.freeze(foz);

console.log("bar" in foo); // true (in chrome & FF4)
console.log(typeof foo["bar"] !== 'undefined'); // true

.

+1

, , . .

Object.prototype.hasOwnProperty.call(null, foo, 'bar')

- , , , , .

+1

, , , if

  • foo EcmaScript 5, bar. , getter . , getter.
  • Internet Explorer 4.0 - in JavaScript 1.4;)

, (Chrome, IE9, FF4):

var foo = {};
Object.defineProperty(foo, "bar", { 
    "get": function () {document.write("Getter invoked!<br/>"); return foo;}
});

document.write('"bar" in foo -->' + 
               ("bar" in foo));
document.write('<br/>');
document.write('typeof foo["bar"] !== "undefined" -->' +
               (typeof foo["bar"] !== "undefined"));
document.write('<br/>');
+1

"bar" foo ( undefined, ), . - .

0

All Articles