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
How to Use Reflection and Object Composition in Modern JavaScript
More Relevant Posts
-
Why You Should Avoid Using new Number(), new String(), and new Boolean() in JavaScript In JavaScript, there is an important distinction between primitive values and object wrappers. Consider the following example: let a = 3; // primitive number let b = new Number(3); // Number object console.log(a == b); // true (type coercion) console.log(a === b); // false (different types) This inconsistency occurs because new Number(), new String(), and new Boolean() create objects, not primitive values. Although they appear similar, they can cause subtle and hard-to-detect bugs in equality checks and logical comparisons. Common Issues Confusing equality checks (== vs ===) Unintended behavior in conditionals or truthy/falsey evaluations Inconsistent data handling across the codebase Recommended Best Practices Always use literals or function calls for primitive values: // Correct usage let x = 3; let y = "Hello"; let z = true; // Safe conversions Number("3"); // → 3 (primitive) String(123); // → "123" Boolean(0); // → false Use constructors like Date, Array, Object, and Function only when you intend to create objects. For Working with Dates Instead of relying solely on the Date object, consider modern and reliable alternatives: Intl.DateTimeFormat for formatting Temporal API (in modern JavaScript runtimes) for date and time arithmetic Key Takeaway If you encounter new Number(), new String(), or new Boolean() in your codebase, it is often a sign of a potential bug. Use literals for primitives, and reserve constructors for actual objects. #JavaScript #WebDevelopment #SoftwareEngineering #ProgrammingBestPractices #CleanCode #FrontendDevelopment #NodeJS #TypeScript #Developers
To view or add a comment, sign in
-
💡 Ever changed a copy of an object… and accidentally changed the original too? If you’ve worked with JavaScript, you know this painful trap all too well! Let’s clarify the difference between shallow copy and deep copy, and see how modern JS handles it. 🔹 Shallow Copy A shallow copy duplicates only the top-level properties. Nested objects or arrays are still shared. const original = { name: "Alice", details: { age: 25 } }; const shallowCopy = { ...original }; shallowCopy.details.age = 30; console.log(original.details.age); // 30 → original object changed! ✅ Top-level copied. ⚠️ Nested objects still reference the same memory. 🔹 Deep Copy A deep copy duplicates everything, including nested objects, so changes don’t affect the original. 1️⃣ Using JSON.stringify() + JSON.parse() const original = { name: "Alice", details: { age: 25 } }; const deepCopy = JSON.parse(JSON.stringify(original)); deepCopy.details.age = 30; console.log(original.details.age); // 25 → safe! ⚠️ Limitation: Doesn’t handle Dates, Maps, Sets, functions, or circular references. 2️⃣ Using structuredClone() (Modern JS) const original = { name: "Alice", details: { age: 25 } }; const deepCopy = structuredClone(original); deepCopy.details.age = 30; console.log(original.details.age); // 25 → safe! ✅ Handles most types, including Date, Map, Set, etc. ⚠️ Available in modern browsers & Node.js v17+. #JS #JavaScript #WebDevelopment #DeepCopy #ShallowCopy #CodingTips #Programming
To view or add a comment, sign in
-
⚡ Write Cleaner Logic with JavaScript Conditionals ✨ Conditionals allow JavaScript to make decisions and execute different code based on different conditions. They are foundational in controlling application logic and user flows. 🔹 1️⃣ if / else — Basic Decision Making Used when you want to execute code based on a true/false condition. if (score >= 40) { console.log("Pass"); } else { console.log("Fail"); } 🔹 2️⃣ else if — Multiple Conditions Useful when you need to check more than one condition in sequence. if (temp > 30) { console.log("Hot"); } else if (temp > 20) { console.log("Warm"); } else { console.log("Cold"); } 🔹 3️⃣ Ternary Operator — Short Form If/Else Compact and commonly used for simpler conditions. let result = age >= 18 ? "Eligible" : "Not Eligible"; ✔ Best for simple expressions ✔ Avoid using ternary for long or nested logic 🔹 4️⃣ switch — Cleaner Multi-Condition Handling Ideal when comparing the same value against multiple possibilities. switch (role) { case "admin": console.log("Access Granted"); break; case "user": console.log("Limited Access"); break; default: console.log("No Access"); } 🔹 5️⃣ Truthy & Falsy Values JavaScript considers some values “false” automatically: Falsy: 0, "", null, undefined, NaN, false Everything else → truthy if (username) { console.log("Valid"); } 🔹 6️⃣ Short-Circuit Evaluation Efficient way to write compact conditions. isOnline && showStatus(); username || "Guest"; && runs the second expression only if the first is true || returns the first truthy value 📌 Professional Summary Use if/else for general decisions Use switch when one value is checked repeatedly Use ternary for simpler expressions Understand truthy/falsy to avoid unexpected behavior Short-circuiting helps create clean, concise logic #JavaScript #FrontendDevelopment #WebDevelopment #CleanCode #ES6
To view or add a comment, sign in
-
-
Going back to basics 🌱 How Javascript executes your code inside the JS Engine ? Let’s say you have a "landing page" that needs a bit of interactivity maybe a "button click". So, you add a JavaScript file to make it all work smoothly. Now, these are are steps that will occure behind the scene - 1. The "Javascript engine" first reads your code from top to bottom, checking if there are any "syntax errors". Then it converts the code into a structured format called an "Abstract Syntax Tree (AST)" basically something the computer can understand. 2. Interpretation : This is where the Javascript engine’s interpreter (like "Ignition" in Chrome’s V8 engine) turns your code into "bytecode" for faster execution. (No need to stress about these , just know this step helps your code run faster, we will explore it more later.) 3. Optimization (JIT) : If you remember, we already discussed "Just-in-time (JIT)" Compilation in an earlier post that’s exactly what happens here. While your page is running, the Javascript engine keeps an eye on which parts of your code run frequently for example, a function that executes every time a button is clicked. When it notices such patterns, the JIT Compiler steps in and converts those parts into machine code, so the next time they run, it happens much faster. 4. Execution : Now, whenever you interact with your page like "clicking a button", the engine runs the already optimised machine code directly. That’s how things happen when you add Javascript to your page. But...but..but , if there is no Javascript file, will the JavaScript engine still work???? #Javascript #Frontend
To view or add a comment, sign in
-
-
💥 JavaScript gotcha of the day: When you think you filled your array with different objects… but JavaScript had other plans 😅 const arr = Array(3).fill({}); // [{}, {}, {}] arr[0].hi = "hi"; console.log(arr); O/p// → [{ hi: "hi" }, { hi: "hi" }, { hi: "hi" }] You expected: [{ hi: "hi" }, {}, {}] but you got copy-paste chaos 🤯 🧠 Why? .fill({}) doesn’t create new objects — it fills the array with the same reference in memory. So arr[0].hi = "hi" updates all of them, because they’re all pointing to the same object! 🛠 Fix it: Use map() or Array.from() to create unique objects 👇 // ✅ distinct objects const arr = Array(3).fill().map(() => ({})); (or) const arr = Array.from({ length: 3 }, () => ({})); Now: arr[0].hi = "hi"; console.log(arr); // [{ hi: "hi" }, {}, {}] #JavaScript #CodingGotchas #WebDevelopment #Frontend #LearningEveryday #JSFun
To view or add a comment, sign in
-
-
🌐 Introduction to JavaScript JavaScript is a lightweight, interactive scripting language that comes with many built-in methods. It plays a key role alongside HTML and CSS to make webpages dynamic and engaging. 🧩 Where JavaScript Is Used JavaScript is used in web development to: Add interactivity Handle user input Communicate with servers for dynamic content 💻 Example Script // Display an alert message window.alert("This is an alert message!"); // Print output to the console console.log("Hello from JavaScript!"); ⚙️ Features of JavaScript ✅ Easy to use ⚡ Fast response time 🔁 Flexible and powerful 🚀 JIT (Just-In-Time) compiler — works as both compiler and interpreter 🧠 Common Console Methods window.alert("Alert message"); console.log("Log message"); console.warn("Warning message"); console.info("Information message"); 📘 console: A built-in JS object giving access to the browser’s debugging console. 🧩 log(), warn(), info() are methods used to print messages or information. 🧱 Objects in JavaScript Objects are collections of properties and methods. Properties (fields): Store data like strings or numbers. Methods (functions): Perform actions. ⚠️ Common JavaScript Errors 1️⃣ Syntax Errors – mistakes in code structure 2️⃣ Reference Errors – using variables not defined 3️⃣ Type Errors – invalid operations on data types 🔡 JavaScript Variables – var, let, const Variables are used to store data values. There are three ways to declare them: var, let, and const 10000 Coders #Frontend #JavaScript #LearningNewThings #WebDevelopment #Coding #Programming
To view or add a comment, sign in
-
-
Demystifying the Prototype in JavaScript If there’s one concept that confuses most developers (even experienced ones), it’s the Prototype. Unlike traditional class-based languages, JavaScript uses prototypal inheritance — meaning objects can inherit directly from other objects. Every JS object has a hidden reference called its prototype, and this is what makes inheritance possible. 🔹 How It Works When you access a property like obj.prop1: 1️⃣ JS first checks if prop1 exists on the object itself. 2️⃣ If not, it looks at the object’s prototype. 3️⃣ If still not found, it continues up the prototype chain until it either finds it or reaches the end. So sometimes a property seems to belong to your object — but it actually lives further down the chain! Example const person = { firstname: "Default", lastname: "Default", getFullName() { return this.firstname + " " + this.lastname; } }; const john = Object.create(person); john.firstname = "John"; john.lastname = "Doe"; console.log(john.getFullName()); // "John Doe" Here’s what happens: JS looks for getFullName on john. Doesn’t find it → checks person (its prototype). Executes the method with this referring to john. Key Takeaways The prototype is just a hidden reference to another object. Properties are looked up the prototype chain until found. The this keyword refers to the object calling the method, not the prototype. Avoid using __proto__ directly — use Object.create() or modern class syntax. One-liner: The prototype chain is how JavaScript lets one object access properties and methods of another — simple, flexible, and core to the language. If you found this helpful, follow me for more bite-sized explanations on JavaScript, React, and modern web development #JavaScript #WebDevelopment #Frontend #React #TypeScript #Coding #LearningInPublic #SoftwareEngineering #TechEducation #WebDevCommunity
To view or add a comment, sign in
-
🚀 Day 30/50 – Function Currying in JavaScript Think of Function Currying like building a relationship. You don’t propose directly 😅 First comes the “Hi Hello 👋” phase → then friendship ☕ → and finally… the proposal ❤️ In JavaScript, instead of passing all arguments at once, Function Currying lets us pass them step by step, each step returning a new function until the final output is achieved. Here’s a simple code analogy from my video: function proposeTo(crush) { return function (timeSpent) { return function (gift) { return `Dear ${crush}, after ${timeSpent} of friendship, you accepted my ${gift}! 🥰`; }; }; } console.log(proposeTo("Sizuka")("3 months")("red rose 🌹")); Each function takes one argument and returns another function — making the code modular, flexible, and easy to reuse. 👉 This is Function Currying — one argument, one step, one perfect result. 🎥 Watch the full short video here: 🔗 https://lnkd.in/g-NkeYBc --- 💡 Takeaway: Function Currying isn’t just a JavaScript trick — it’s a powerful pattern for cleaner, more composable functions that enhance reusability and maintainability in modern frontend code. --- Would love to know: 👉 What’s your favorite JavaScript concept that clicked instantly when you saw it explained simply? #javascript #frontenddevelopment #webdevelopment #coding #programming #softwareengineering #learnjavascript #100daysofjavascript #techsharingan #developers #careergrowth
To view or add a comment, sign in
-
JavaScript Simplified: Destructuring & Spread Operator Ever noticed how JavaScript lets you write cleaner and shorter code? That’s where Destructuring and the Spread Operator (...) come in! What is Destructuring? Destructuring means “unpacking” values from arrays or objects into variables— instead of accessing each one manually. const user = { name: "Sameer", age: 22 }; const { name, age } = user; console.log(name, age); // Sameer 22 You can even rename or set default values: const { country: location = "India" } = user; What is the Spread Operator (...)? The spread operator helps you copy, merge, or expand arrays and objects effortlessly. const fruits = ["apple", "banana"]; const moreFruits = ["orange", "grapes"]; const allFruits = [...fruits, ...moreFruits]; console.log(allFruits); // ["apple", "banana", "orange", "grapes"] It also works great with objects: const user = { name: "Sameer", age: 22 }; const updatedUser = { ...user, age: 23 }; console.log(updatedUser); // { name: "Sameer", age: 23 } In short: Destructuring → Pull out values easily Spread → Copy or merge effortlessly #JavaScript #WebDevelopment #Frontend #CodingTips #Destructuring #SpreadOperator #LearnJS
To view or add a comment, sign in
-
Ever wondered how JavaScript functions remember things? The secret is Closures! 🤫 A closure is a fundamental JS concept where a function remembers the variables from its outer scope, even after that outer function has finished executing. 🚀 **Why They're Powerful:** Closures are the backbone of many advanced JavaScript patterns. They enable: 🔹 **Data Encapsulation:** Creating private variables and methods, which is crucial for protecting your data from the global scope. Think of it as a private vault for your function's state. 🔹 **Function Factories:** Building functions that can generate other functions with specific, pre-configured settings. 🔹 **Maintaining State:** Powering callbacks and event handlers in asynchronous operations, allowing them to access the variables they need long after they were created. 🤔 **Why They're Tricky:** With great power comes potential pitfalls. Closures can be tricky if you're not careful: 🔸 **Memory Leaks:** Since closures hold references to their outer scope variables, they can prevent the garbage collector from cleaning up memory if not managed properly. 🔸 **Stale Data:** In loops, closures can accidentally capture the same variable reference, leading to all of them using the final value of the loop, which can cause unexpected bugs. Mastering closures is a rite of passage for any JavaScript developer. Understanding them unlocks a new level of control, enabling you to write more modular, elegant, and robust code. What are your favorite use cases or tricky moments with closures? Share in the comments! 👇 #JavaScript #WebDevelopment #Programming #Coding #Developer #Closures #SoftwareEngineering #Frontend #TechTips #LearnToCode #JS
To view or add a comment, sign in
-
More from this author
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development