How do objects work in JavaScript?
An object is a collection of key and value pairs. A key is a string or a symbol, and a value can be anything at all, including another object or a function. Objects are the base of almost everything else in JavaScript. Arrays are objects, functions are objects, and even a date is an object.
const user = {
name: 'Ada',
greet() { return 'Hi ' + this.name; }
};
console.log(user.name); // Ada
console.log(user.greet()); // Hi Ada
console.log(typeof user); // object
console.log(Object.keys(user)); // [ 'name', 'greet' ]
console.log('name' in user); // true
console.log(user.hasOwnProperty('name')); // true
console.log(Object.entries(user)); // [ [ 'name', 'Ada' ], [ 'greet', [Function] ] ]
A property that holds a function is called a method. The important point is that a method is not owned by the object in any special way. It is simply a value that is stored under a key. When you call it as a method, the object is passed to the function as the receiver, and that is where the this binding comes from.
There are three ways to ask whether a property exists, and they are not the same. The in operator checks the object and its prototype chain, so it also finds inherited properties. The hasOwnProperty method checks only the object itself, and it is the one to use when you care about own properties. The third option is to check the value, and that one cannot tell a missing property apart from a property that holds an empty value.
Every object also has a prototype, and property lookup walks the prototype chain until it finds a match. The chain has its own set of questions, but the practical point for this answer is that a plain object literal inherits from the shared object prototype. That is why toString and valueOf are available on every value.