🔍 Prototypes and this in JavaScript — going beyond the syntax into the actual mechanics. Here's what's worth knowing: 🧬 On Prototypes Methods aren't copied to every object instance. They live once on the prototype — all instances share them via reference. That's how JS stays memory efficient even with thousands of objects. Every method lookup is a live chain traversal, every single time. Object.create is pure prototype wiring — it sets the [[Prototype]] of a new object. That's it. 🎯 On this — four rules, in priority order 1️⃣ new binding → this = newly created object 2️⃣ Explicit binding → .call() .apply() .bind() — you decide 3️⃣ Implicit binding → obj.method() — this = object left of the dot 4️⃣ Default binding → standalone call — this = window or undefined Arrow functions sit outside all four rules — they inherit this lexically from wherever they were defined. ⚠️ The classic trap js setTimeout(this.log, 1000); // this is lost Detach a method from its object and this evaporates. Fix → arrow wrapper, .bind(), or bind in the constructor. Each has different tradeoffs. 🧠 On EventEmitters and memory Per-instance state must always be initialized in the constructor. If it accidentally lands on the prototype — every instance shares the same object. Emitting on one instance fires callbacks registered on all instances. Silent. No error thrown. Every .on() listener holds a closure reference — keeping objects alive in memory long after they're "destroyed." Always implement .off(). Always clean up. Follow along — sharing one deep dive at a time. 🚀 #JavaScript #Prototypes #FrontendEngineering #WebPerformance #PlatformEngineering
Prototypes in JavaScript: Methods, Binding, and Memory Efficiency
More Relevant Posts
-
𝗧𝗵𝗲 𝗘𝘃𝗲𝗻𝘁 𝗟𝗼𝗼𝗽: 𝗠𝗶𝗰𝗿𝗼𝘁𝗮𝘀𝗸𝘀 𝗮𝗻𝗱 𝗠𝗮𝗰𝗿𝗼𝘁𝗮𝘀𝗸𝘀 You write JavaScript code that handles thousands of requests per second. But do you really understand the event loop? Let's break it down: - Your code runs on a call stack, one function at a time. - When you call setTimeout or fetch, you hand the task to an assistant. - The assistant places a note on a task queue when it's done. - The event loop checks the stack, then the task queue. But here's the thing: there are two queues - macrotasks and microtasks. - Macrotasks include setTimeout, setInterval, and I/O events. - Microtasks include Promise callbacks and queueMicrotask. The event loop has a rule: after every macrotask, it empties the microtask queue. This changes how you write your code. For example: - console.log('1') - setTimeout(() => console.log('2'), 0) - Promise.resolve().then(() => console.log('3')) - console.log('4') The output will be 1, 4, 3, 2. Microtasks always run before the next macrotask. To write better code: - Use setTimeout when you want to yield to the UI. - Use queueMicrotask or Promise when you need something to happen immediately. Understanding the event loop will save you from: - Blocking the event loop with synchronous loops - Mis-ordering critical database updates - Building unreliable real-time systems You place the marbles, the engine moves them. It's your understanding of the track that determines the performance. Draw the queues, ask yourself: Is this a macrotask? A microtask? Respect the choreography, and the engine will reward you with silky-smooth performance. Source: https://lnkd.in/g--B86YF
To view or add a comment, sign in
-
Ever copied an object in JavaScript… and later wondered why changing one thing broke something else? I used the spread operator, Object.assign—everything looked right. The object was “copied,” features worked, and I moved on. Until one small change inside a nested object started affecting the original data. That’s when I realized copying in JavaScript isn’t as straightforward as it looks. I used to think: “If I copy an object, I get a completely separate version.” Sounds reasonable—but it misses an important detail. So I slowed down and explored what was actually happening. References. Memory locations. Nested structures. I built tiny examples, tweaked values, compared outputs—sometimes it worked, sometimes it didn’t… until patterns started to show up. And then it made sense. The issue wasn’t the syntax—it was understanding what gets copied and what still points to the same place in memory. That shift changed a lot: • I stopped assuming copies were independent • Debugging weird state changes became much easier • Spread vs structuredClone finally had a clear difference • Nested objects stopped feeling unpredictable Most importantly: 👉 A shallow copy duplicates only the top level 👉 Nested objects still share the same reference 👉 A deep copy creates a fully independent structure Now when something changes unexpectedly, I don’t guess—I check how the data was copied. Still learning, but this one concept made JavaScript feel a lot more predictable. What’s one JS concept that took you time to truly understand? #JavaScript #WebDevelopment #Frontend #LearningInPublic #JSConcepts #Debugging
To view or add a comment, sign in
-
-
💡 Think semicolons don’t matter in JavaScript? Think again. Here’s a subtle but powerful concept: Automatic Semicolon Insertion (ASI). At first glance, this code looks perfectly fine: const arr = [1, 2, 3] (function () { console.log("Hello 👋") })() But instead of printing "Hello 👋", it throws: ❌ TypeError: arr is not a function 👉 Why? JavaScript doesn’t automatically insert a semicolon after the array declaration. So it interprets the code like this: const arr = [1, 2, 3](function () { ... })() Now it tries to call arr as a function — and arrays aren’t callable. ✅ The Fix is simple: const arr = [1, 2, 3]; (function () { console.log("Hello 👋") })() Now everything works as expected. 🔍 Key Takeaways: • JavaScript uses ASI, but it’s not always reliable • Starting a line with (, [, or + can cause unexpected behavior • Missing semicolons can silently change how your code is interpreted • Always be explicit when your next line starts with an IIFE or expression 🚀 Pro Tip: Even if you prefer a “no-semicolon” style, make sure to add one before IIFEs or tricky expressions to avoid bugs that are hard to debug. ⚡ JavaScript isn’t just about writing code — it’s about understanding how the engine reads your code. #JavaScript #WebDevelopment #CodingTips #Frontend #Programming #CleanCode
To view or add a comment, sign in
-
-
💡 JavaScript Tip: Start using the .at(-1) today! If you're still accessing the last element of an array like this: arr[arr.length - 1] There’s a cleaner and more readable way 👇 arr.at(-1) 🔹 Why use .at()? ✅ Cleaner syntax ✅ Easier to read ✅ Supports negative indexing 🔹 Examples const nums = [10, 20, 30, 40]; nums.at(0); // 10 nums.at(2); // 30 nums.at(-1); // 40 (last element) nums.at(-2); // 30 🔹 When to use it? Accessing last or second-last elements Writing cleaner, more modern JavaScript Avoiding repetitive .length calculations ⚠️ Note .at() works in modern JavaScript (ES2022+), so ensure your environment supports it. Small improvements like this can make your code more readable and elegant ✨ Are you using .at() already? #JavaScript #CleanCode #WebDevelopment #FrontendDevelopment #ProgrammingTips #DevCommunity #SoftwareEngineering
To view or add a comment, sign in
-
-
💡 JavaScript Hidden Power: Arithmetic on Objects?! At first glance, applying arithmetic operators (+, -, *, /) on objects looks impossible… but JavaScript surprises us again. Take this example 👇 When we define a valueOf() method inside an object, JavaScript knows how to convert that object into a primitive number when needed. 👉 That’s exactly what’s happening here: obj1.valueOf() → returns 10 obj2.valueOf() → returns 20 So when we do: obj2 - obj1 → 20 - 10 = 10 obj2 + obj1 → 20 + 10 = 30 and so on… 🔍 Why does this work? JavaScript uses a concept called type coercion. Whenever an object is used with arithmetic operators: JS tries to convert it into a primitive value It calls: valueOf() first If not usable, then toString() 📅 What about Date objects? Date objects follow the same rule! const d1 = new Date('2026-03-25'); const d2 = new Date('2026-03-26'); console.log(d2 - d1); // 86400000 (difference in milliseconds) 👉 Why? Because Date.valueOf() returns the timestamp (milliseconds since Jan 1, 1970) 🚀 Key Takeaway JavaScript isn’t just loosely typed — it’s intelligently flexible. By customizing valueOf(): You can control how objects behave in calculations Build smarter abstractions Write more expressive code ⚠️ Pro Tip Avoid overusing this in production unless it improves clarity — unexpected coercion can confuse other developers. 🔥 JavaScript looks simple… until it isn’t. #JavaScript #WebDevelopment #MERN #Frontend #Programming #DevTips #reactjs #nodejs
To view or add a comment, sign in
-
-
JavaScript objects have a powerful feature called Prototype that enables inheritance. In JavaScript, if an object doesn’t have a specific property or method, the engine automatically looks for it in its prototype. This process continues up the prototype chain until the property is found or the chain ends. Example: function Person(name) { this.name = name; } Person.prototype.greet = function () { console.log("Hello, my name is " + this.name); }; const john = new Person("John"); john.greet(); Even though john doesn’t directly have the greet() method, it can still access it through Person.prototype. This mechanism allows JavaScript objects to share methods and inherit behavior efficiently. Understanding prototypes helps you better understand how inheritance and object behavior work behind the scenes in JavaScript. Follow for more JavaScript concepts explained visually. #javascript #webdevelopment #frontenddeveloper #coding #learninginpublic #100DaysOfCode
To view or add a comment, sign in
-
-
Shipping is a habit! 🚀 2 Days, 2 Projects, and a deeper dive into JavaScript. I’ve been heads-down in the #ChaiAurCode journey, and the momentum is real. Over the last 48 hours, I’ve moved from understanding basic logic to shipping functional mini-projects. Project 1: Dynamic List Creator 📝 Focused on mastering the DOM. It’s one thing to see a list on a screen, it’s another to handle real-time user input, state updates, and clean element creation dynamically. 🌐 Try the List Creator: https://lnkd.in/grMrRqMt Project 2: Color Palette Generator 🎨 This one was a technical "Aha!" moment. 🌐 Try the Palette Generator: https://lnkd.in/gCUwyhrc Key takeaways: ➡️ Precision Math: Implementing Math.random() * (max - min) + min to control color tones (Light vs. Dark). ➡️ String Manipulation: Using .padStart(2, "0") to ensure valid Hex codes a small detail that prevents major UI bugs. ➡️ The Backend Loop: I even experimented with running an Express server and frontend logic in a single file to visualize the full Request-Response cycle. Big thanks to my mentors Hitesh Choudhary and Suraj Kumar Jha for the guidance during the T-class sessions! Github repo links - List Creator - https://lnkd.in/gH9hzGY3 Palette Generator - https://lnkd.in/gEAv7NJ4 (I've shared the screen recording for the List Creator in the comments below! 👇) Anirudh J. Akash Kadlag Jay Kadlag Piyush Garg #WebDevelopment #JavaScript #BuildInPublic #FullStackJourney #LearningTogether #Vercel #CodingProgress
To view or add a comment, sign in
-
Say Goodbye to JavaScript Date Object Headaches! For years, developers have struggled with the built-in Date object in JavaScript—it's mutable, inconsistent, and a major pain when dealing with time zones or complex date arithmetic. Most of us have relied on external libraries like Moment.js or date-fns to get the job done. But the future is here: the Temporal API is arriving as a new built-in standard, and it's a game-changer! 🚀 Temporal provides a robust, modern, and reliable way to handle dates and times. Here’s why you should be excited: 🔒 Immutability: Every Temporal object is immutable, which eliminates a major source of bugs in date manipulation. 🌍 First-Class Time Zones: It has explicit, robust support for time zones and daylight saving time (DST). ➗ Safe Arithmetic: Performing calculations like adding or subtracting days is predictable and straightforward with methods like add() and subtract(). 🎯 Clear Data Types: Instead of one generic Date object, Temporal offers distinct types for different use cases: Instant: For exact points in time. PlainDate, PlainTime, PlainDateTime: For wall-clock dates and times without a specific time zone. ZonedDateTime: For handling time-zoned timestamps. Major browsers are actively implementing the proposal. You can start experimenting with it today using a polyfill or check out the official TC39 documentation. It's time to level up our date-handling skills! Who's ready to make the switch? #JavaScript #WebDev #Frontend #Temporal #Programming #Coding #TechNews
To view or add a comment, sign in
-
-
While working with the DOM in JavaScript, I discovered something that confuses many developers (including me earlier). NodeList vs HTMLCollection Both look similar, but they behave differently — and this can affect your code. Here’s the simple explanation 👇 Example 1: const items = document.querySelectorAll("li"); This returns a NodeList Example 2: const items = document.getElementsByTagName("li"); This returns an HTMLCollection Now the important difference ⚡ If you add a new element to the DOM: NodeList → ❌ Does NOT update automatically HTMLCollection → ✅ Updates automatically (Live) Another difference: NodeList supports forEach() items.forEach(item => console.log(item)); HTMLCollection does not support it directly: Array.from(items).forEach(item => console.log(item)); __________________________________________________________________________________ ⚡ Quick Way to Remember NodeList → querySelectorAll() → Static list HTMLCollection → getElementsBy...() → Live list __________________________________________________________________________________ This is a very common frontend interview question and also important when working with DOM manipulation. Have you ever faced a bug because of this difference? 👇 Chai Aur Code Hitesh Choudhary Piyush Garg #Web Dev Cohort 2026 #javascript #frontenddevelopment #webdevelopment #dom #coding #learninpublic
To view or add a comment, sign in
-
-
🔍 JavaScript Logic That Looks Simple… But Isn’t! Ever wondered how this works? 👇 if (!isNaN(str[i]) && str[i] % 2 == 0) { console.log(str[i]); } Let’s break it down: Suppose: let str = "a1b2c3d4"; 🔹 Step 1: str[i] Gives each character → "a", "1", "b", "2"... 🔹 Step 2: !isNaN(str[i]) Checks if the character can be converted to a number "2" → valid number ✅ "a" → not a number ❌ 🔹 Step 3: str[i] % 2 == 0 JavaScript converts "2" → 2 Then checks if it’s even ⚡ Hidden Magic: Short-Circuit (&&) If the first condition fails, JavaScript skips the second condition So for "a": !isNaN("a") → false % 2 is never executed 🚫 ✅ Final Output: 2 4 🚀 Key Takeaways: ✔ JavaScript automatically converts strings to numbers in calculations ✔ isNaN() helps filter numeric values ✔ && prevents errors using short-circuiting 💬 Clean logic like this is often used in string parsing & interview problems Would you like more such real-world JS tricks? 👇 #JavaScript #WebDevelopment #Coding #100DaysOfCode #LearnToCode
To view or add a comment, sign in
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