Sub topic 2
Checking Whether a Property Exists
This chapter assumes you can create objects with literals and read their properties with dot and bracket notation. It covers four related tools: existence checks, methods and this, enumeration order, and destructuring.
Checking Whether a Property Exists
Reading a missing property returns undefined. A property can also exist and hold undefined as its value, so that check can't tell the two cases apart. Use one of these instead:
key in objreturns true for own and inherited properties.Object.hasOwn(obj, key)returns true only for own properties.obj.a?.b(optional chaining) returnsundefinedinstead of throwing whenobj.aisnullorundefined.
const proto = { inherited: true };
const obj = Object.create(proto);
obj.own = undefined;
console.log("own" in obj); // true
console.log("inherited" in obj); // true
console.log(Object.hasOwn(obj, "inherited")); // false
console.log(obj.missing?.deep); // undefined
delete obj.own;
console.log("own" in obj); // falseMethods and How this Is Bound
A method is a function stored as a property. Inside a method, this is the object before the dot at the moment of the call. It is not the object where the method was defined.
const counter = {
count: 0,
increment() {
this.count++;
return this.count;
}
};
console.log(counter.increment()); // 1
const bound = counter.increment.bind(counter);
console.log(bound()); // 2Listing Properties and Their Order
Object.keys, Object.values, and Object.entries list own enumerable string keys. for...in also visits inherited enumerable keys. The order is fixed: integer-like keys come first in ascending order, then the other string keys in insertion order.
const o = { b: 1, 2: "two", a: 2, 1: "one" };
console.log(Object.keys(o)); // ["1", "2", "b", "a"]
for (const [k, v] of Object.entries(o)) {
console.log(k, v);
}Unpacking Objects with Destructuring
Destructuring copies properties into variables. A default value applies only when the property is undefined. A rest element (...rest) collects the remaining own enumerable properties into a new object.
const user = { id: 7, profile: { name: "Lin" } };
const { id, role = "guest", ...rest } = user;
console.log(id); // 7
console.log(role); // "guest"
console.log(rest); // { profile: { name: "Lin" } }Exercise
What does Object.keys({ z: 1, 10: "a", y: 2, 3: "b" }) return, and why?
Show answer
["3", "10", "z", "y"]. Integer-like keys are listed first in ascending numeric order, then the string keys follow in insertion order.
Exercise
Given const obj = { x: undefined }, what do obj.x === undefined, "x" in obj, and Object.hasOwn(obj, "y") return?
Show answer
true, true, and false. The property x exists but holds undefined, so only the in check shows that it exists. The object has no y property.