MENU
Operators for Objects
So far we have used the . and [] operators on an object.
'new' 'new' 'new' instantiates an object out of a pre-defined type, ie. not from a literal. Applying the 'typeof'typeof' 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''instanceof' 'instanceof' tests if an object is an instance of a type.
RESETRUNFULL
<!DOCTYPE html><html><body><script>
var o={p:100};console.log(typeof o); // objectconsole.log(typeof typeof o); // string
var o2 = new Object();o.o=100;console.log(o==o2); // falseconsole.log(typeof o === typeof o2); // true
var o3={p:100};console.log(o==o3); // false
var o4=o;console.log(o===o4); // true
console.log(o2 instanceof Object); // trueconsole.log(o instanceof Object); // true
</script></body><html>
'in' 'in' '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.
RESETRUNFULL
<!DOCTYPE html><html><body><script>
var o={p:10}, X="p";
console.log(X in o); // true
console.log("p" in o); // true // console.log(p in o); // ReferenceError
</script></body><html>
You can use the optinal chaining operator (?) to access possibly nested properties without raising an error.
RESETRUNFULL
<!DOCTYPE html><html><body><script>
const o = {a:1, b:{c:2}};console.log(o.b?.c); // 2console.log(o.c?.c); // undefined//console.log(o.c.c); // TypeError
</script></body><html>