MENU
Operators for Objects
So far we have used the . and [] operators on an object.
'new' instantiates an object out of a pre-defined type, ie. not from a literal. Applying the 'typeof'operator on an object returns the “object” string. Two objects are never equal unless the two variables point to the same object in memory. 'instanceof' tests if an object is an instance of a type.
var o = {p: 100};
console.log(typeof o);
console.log(typeof typeof o);
var o2 = new Object();
o.o = 100;
console.log(o == o2);
console.log(typeof o === typeof o2);
var o3 = {p: 100};
console.log(o == o3);
var o4 = o;
console.log(o === o4);
console.log(o2 instanceof Object);
console.log(o instanceof Object);object
string
false
true
false
true
true
true
'in' tests if a string is a property name of an object. It can be used to check the existence of a property in an object.
var o = {p: 10}, X = "p";
console.log(X in o);
console.log("p" in o);
// console.log(p in o); // ReferenceErrortrue
true
You can use the optinal chaining operator (?) to access possibly nested properties without raising an error.
const o = {a: 1, b: {c: 2}};
console.log(o.b?.c);
console.log(o.c?.c);
// console.log(o.c.c); // TypeError2
undefined