Objects are JavaScript's core data structure, and two things about them trip people up constantly: the this keyword inside methods, and the fact that objects are copied by reference, not value. Nail these and you'll avoid a whole category of bugs.
Methods & this
A method is a function stored on an object. Inside it, this refers to the object the method was called on:
const student = {name: "Aanya",package: 8,raise(pct) {this.package *= 1 + pct / 100; // this = studentreturn this.package;},};student.raise(25); // 10
The this trap
this depends on how a function is called, not where it's defined. Passing a method as a callback loses its this. Arrow functions fix this — they don't have their own this, so they keep the surrounding one:
const timer = {seconds: 0,// ✗ regular function: 'this' is wrong when called by setIntervalstartBroken() {setInterval(function () { this.seconds++; }, 1000); // this ≠ timer},// ✓ arrow keeps the surrounding 'this'start() {setInterval(() => { this.seconds++; }, 1000); // this = timer},};
Copying vs referencing
const a = { placed: false };const b = a;b.placed = true;a.placed // true — same object!// Make a shallow copy with spread:const copy = { ...a, placed: false }; // independent (top level)const arrCopy = [...arr];
Iterating objects
const s = { name: "Aanya", package: 8 };Object.keys(s) // ["name", "package"]Object.values(s) // ["Aanya", 8]Object.entries(s) // [["name","Aanya"], ["package",8]]for (const [key, value] of Object.entries(s)) {console.log(key, value);}
Prototypes
JavaScript's inheritance is prototype-based: every object has a hidden link to a "prototype" object, and looking up a property that isn't on the object continues up that chain. This is why [].map works — map lives on Array.prototype, not on your array. Classes (next chapter) are friendly syntax over this same mechanism.
Practice
Build a counter object with a count and an increment() method used inside a setInterval — first with a regular function (watch it break) then an arrow (watch it work). Then demonstrate the reference-copy trap and fix it with spread.
Key takeaways
- 01A method is a function on an object; inside it, this is the object it was called on.
- 02this depends on how a function is called — arrow functions inherit the surrounding this.
- 03Objects/arrays are held by reference; assignment shares them — copy with spread {...obj}/[...arr].
- 04Iterate with Object.keys/values/entries.
- 05JS inheritance is prototype-based; array/string methods live on the prototype chain.
