Reputation: 138
The variable 'bar' are all undefined. But is there any difference between obj.bar
and obj2.bar
?
const obj = { foo: "foo" };
console.log(obj); // { foo: 'foo' }
console.log(obj.bar); // undefined
const obj2 = { foo: "foo", bar: undefined };
console.log(obj2); // { foo: 'foo', bar: undefined }
console.log(obj2.bar); // undefined
Upvotes: 1
Views: 43
Reputation: 167182
In the first case, the bar
is not declared. But in the second case, the bar
is declared and defined to undefined
.
Pretty tricky, the way to find it is, if you use Object.keys(obj)
, you can't find bar
.
Also, using obj.hasOwnProperty('bar')
will give you false. Thanks to deceze♦ for pointing it out.
const obj = { foo: "foo" };
// console.log(obj); // { foo: 'foo' }
// console.log(obj.bar); // undefined
const obj2 = { foo: "foo", bar: undefined };
// console.log(obj2); // { foo: 'foo', bar: undefined }
// console.log(obj2.bar); // undefined
console.log(Object.keys(obj));
console.log(Object.keys(obj2));
console.log(obj.hasOwnProperty('bar'));
console.log(obj2.hasOwnProperty('bar'));
Upvotes: 3