Where do methods come from?
Every array has .map, every string has .toUpperCase — but you never wrote those onto your arrays. They live on a shared object called a prototype. When JavaScript can't find a property on an object, it looks up the chain.
The prototype chain
const animal = {
speak() {
return this.name + " makes a sound";
},
};
const dog = Object.create(animal);
dog.name = "Kale";
console.log(dog.speak());
console.log(Object.hasOwn(dog, "speak"));
console.log(Object.getPrototypeOf(dog) === animal);Asking the family: If you don't know a recipe, you ask your mother; if she doesn't know, she asks hers. Property lookup walks up the family tree the same way, until it finds the answer or runs out of ancestors (null).
const list = [3, 1, 2];
console.log(Object.getPrototypeOf(list) === Array.prototype);
console.log(Object.hasOwn(Array.prototype, "map"));
console.log(Object.keys({ a: 1 }));
console.log("a" in { a: 1 }, "toString" in { a: 1 });