How to Use Reflection and Object Composition in Modern JavaScript

Reflection & Object Composition in Modern JavaScript In JavaScript, objects don’t just store values — they can look at themselves and manipulate their own properties. That’s the power of Reflection. Reflection enables patterns like Object Composition, a clean, modern alternative to long prototype chains. Reflection in Action const john = { firstname: "John", lastname: "Doe" }; for (let prop in john) { if (john.hasOwnProperty(prop)) { console.log(prop + ": " + john[prop]); } } Output: firstname: John lastname: Doe Object Composition — the ES6+ Way Instead of relying on libraries like Lodash or Underscore, modern JS gives us built-ins: 1️⃣ Object.assign() Object.assign(john, { address: "123 Main St" }, { getFirstName() { return this.firstname; } }); 2️⃣ Spread Operator (ES2018) const extendedJohn = { ...john, address: "123 Main St", getFirstName() { return this.firstname; } }; Object.assign() → Mutates the object Spread { ...obj } → Creates a new one Why It Matters No external libraries needed Clean, readable syntax Full control over mutation or immutability 100% native and widely supported Takeaway: With ES6+, Object.assign() and the spread operator { ...obj } give you all the power of extend, natively — Reflection + Composition, the modern way. #JavaScript #ES6 #FrontendDevelopment #WebDevelopment #CleanCode #ProgrammingTips #React #TypeScript

To view or add a comment, sign in

Explore content categories