Object Methods and 'this'
JavaScript provides built-in helpers for inspecting objects, and understanding how this behaves in methods is essential for avoiding bugs.
const product = { name: "Book", price: 300 };
Object.keys(product); // ["name", "price"]
Object.values(product); // ["Book", 300]
Object.entries(product); // [["name", "Book"], ["price", 300]]
const counter = {
count: 0,
increment() {
this.count++; // 'this' refers to counter here
},
};
counter.increment();
Regular function methods get this bound dynamically to whatever object called them — counter.increment() binds this to counter. Arrow functions used as object methods do not get this binding — they capture this from the enclosing (often global or module) scope instead, which is a common source of bugs when developers reach for arrow syntax inside object literals expecting this to behave like a regular method.
Object.entries() pairs especially well with for...of and destructuring for iterating over an object's key-value pairs directly.