Group related values and behavior
An object stores properties addressed by keys. A method is a callable property used through an object. Dot notation suits a known identifier; bracket notation suits a computed key or a name that is not a normal identifier.
const student = {
name: 'Asha',
completed: 2,
finishLesson() {
this.completed += 1;
return this.completed;
}
};
console.log(student.name); // Asha
const field = 'completed';
console.log(student[field]); // 2
console.log(student.finishLesson()); // 3this depends on the call
In the shown method call, this is student. Extracting the method into a standalone variable does not retain that receiver automatically. Use an explicit wrapper or bind when a callback needs a particular receiver.
const finish = student.finishLesson.bind(student);
console.log(finish()); // 4Arrow functions have lexical this instead; placing an arrow inside an object literal does not turn it into a method with object-bound this.
Identity, ownership and existence
Assigning the object to another variable shares the same object reference. A spread copy is shallow. To distinguish an absent property from an own property whose value is undefined, use Object.hasOwn on supported runtimes or an appropriate compatibility method. The in operator also checks the prototype chain.
const profile = { nickname: undefined };
console.log(profile.nickname); // undefined
console.log(Object.hasOwn(profile, 'nickname')); // true
console.log(Object.hasOwn(profile, 'missing')); // falseSafe design boundaries
Do not copy arbitrary untrusted fields into an authorization object or assume a client-supplied role is trusted. Enumerate allowed fields and validate their types. For dynamic arbitrary-key collections, a Map may express intent better than a plain object.
Practice
- Add a reset method that sets completed to zero.
- Read a property using a user-selected field name from a fixed allowlist.
- Create two equal-looking objects and compare them with ===; expect false because identities differ.
- Explain why a bound function continues to update student after being stored separately.