📌 Just finished reading the JavaScript documentation on Prototypes — here's what I actually understood 🧵 I spent time going through the official MDN docs on JavaScript prototypes, and wanted to share here— 🔺 What is a Prototype? Every object in JavaScript has a hidden internal link to another object — called its prototype. Think of it as a "parent" object that the current object can borrow properties and methods from. When you try to access a property on an object and it's not found directly on that object, JavaScript automatically looks up to its prototype. If it's not there either, it goes up again — until it reaches null. This chain of lookups is called the prototype chain. 🔺 Why does this exist? JavaScript needed a way to share behavior across multiple objects without duplicating code or wasting memory. Instead of giving every object its own copy of a method, you define the method once on a prototype — and all objects linked to that prototype can use it. This is memory-efficient and keeps things organized. 🔺 How it works — a simple example: function Person(name) { this.name = name; } // Adding a method to the prototype Person.prototype.greet = function () { console.log("Hi, I'm " + this.name); }; const alice = new Person("Alice"); const bob = new Person("Bob"); alice.greet(); // Hi, I'm Alice bob.greet(); // Hi, I'm Bob // Both share the SAME greet function — not two separate copies console.log(alice.greet === bob.greet); // true Here, greet lives on Person.prototype — not on alice or bob individually. JavaScript finds it by walking up the prototype chain. 🔺 When do you actually use this in real projects? Constructor functions — before ES6 classes, this was the standard way to create objects with shared behavior. Shared methods — placing utility methods on a prototype so all instances access one definition. Memory efficiency — especially relevant when creating many instances of the same object type. Understanding built-ins — methods like .map(), .filter(), .toString() all live on prototype objects (Array.prototype, Object.prototype, etc.). 🔺 One thing that tripped me up: The difference between an object's prototype (accessed via Object.getPrototypeOf(obj)) and the prototype property on a constructor function (Person.prototype) — they're related but not the same thing. Worth reading carefully. 🔺 My question to other developers: Do you think understanding prototypes is still essential for modern JavaScript development, or is it more of a "good to know" concept now? Would love to hear how others think about this. 👇 #JavaScript #WebDevelopment #Frontend #LearnInPublic #JS
JavaScript Prototypes: Understanding the Chain
More Relevant Posts
-
🚨 JavaScript Objects Confused Me… Until I Understood This One Thing When I started learning JavaScript, I thought objects were simple. Then I saw terms like object literals, constructor functions, "this", prototypes, "Object.create()"… And suddenly my brain went: "Wait… what is actually happening here?" 🤯 But once the puzzle clicked, everything started making sense. Here’s the simplest way I now understand JavaScript objects 👇 --- 🔹 1️⃣ Object Literals — The simplest way to create objects const user = { name: "Alex", age: 25 }; Clean. Simple. And used most of the time. --- 🔹 2️⃣ Constructor Functions — Blueprint for multiple objects function User(name, age) { this.name = name; this.age = age; } const u1 = new User("Alex", 25); Here, "this" refers to the new object being created. Think of it like a template for creating many similar objects 🧩 --- 🔹 3️⃣ Prototypes — JavaScript’s hidden superpower Instead of copying methods into every object, JavaScript shares them through prototypes. User.prototype.greet = function() { console.log("Hello!"); }; Now every "User" object can access "greet()" without duplicating memory 🚀 --- 🔹 4️⃣ Object.create() — Direct control over prototypes const person = { greet() { console.log("Hi!"); } }; const user = Object.create(person); This creates an object that inherits directly from another object. Simple concept. Very powerful in practice. --- 🔹 5️⃣ The "let" & "const" confusion with arrays and objects This confused me for a long time 👇 const arr = [1,2,3]; arr.push(4); // ✅ Works But this fails: const arr = [1,2,3]; arr = [4,5,6]; // ❌ Error Why? Because "const" protects the reference, not the content. Objects and arrays are reference types, so their internal values can change. But primitive values cannot: const a = 10; a = 20; // ❌ Error --- 🔥 Once you understand this: • Objects store references • Prototypes enable shared behavior • "this" depends on how a function is called JavaScript suddenly becomes much easier to reason about. And honestly… much more fun to work with. 🚀 --- 💬 If you're learning JavaScript: What concept confused you the most at first? Let’s help each other grow 👇 --- #javascript #webdevelopment #frontenddevelopment #softwaredevelopment #coding #programming #developer #100daysofcode #learnjavascript #codinglife #techlearning
To view or add a comment, sign in
-
💡 JavaScript Concept: setTimeout vs clearTimeout If you’ve worked with asynchronous JavaScript, you’ve probably used setTimeout. But many developers overlook its partner function — clearTimeout. Let’s understand both. ⏳ setTimeout setTimeout is used to execute a function after a specified delay. setTimeout(() => { console.log("Hello after 2 seconds"); }, 2000); 📌 What happens here? • The function is scheduled to run after 2000 milliseconds (2 seconds) • JavaScript places it in the Web APIs environment • After the delay, it moves to the callback queue and waits for the call stack to be empty 🛑 clearTimeout clearTimeout is used to cancel a scheduled timeout before it executes. function showMessage() { console.log("This will not run"); } const timerId = setTimeout(showMessage, 3000); clearTimeout(timerId); 📌 What happens here? • setTimeout returns a timer ID • clearTimeout(timerId) cancels the scheduled task • The callback never executes 🧠 Output Based Question What will be the output? const timer = setTimeout(() => { console.log("Task executed"); }, 1000); clearTimeout(timer); console.log("Program finished"); ✅ Output Program finished Because the timeout was cleared before the callback could execute. ⚡ Real-world Use Cases ✔ Cancelling delayed UI actions ✔ Debouncing search inputs ✔ Stopping unnecessary API calls ✔ Cleaning up timers in components ✨ Key Takeaway setTimeout → schedules a function to run later clearTimeout → cancels that scheduled execution
To view or add a comment, sign in
-
🔥 JavaScript Deep Dive: Understanding this, call(), apply(), and bind() One of the most important concepts in JavaScript is understanding how function context works. Many developers get confused with the behavior of the this keyword and how it changes depending on how a function is called. To control the value of this, JavaScript provides three powerful methods: call(), apply(), and bind(). Understanding these concepts is essential for writing clean, reusable, and predictable JavaScript code, especially when working with callbacks, event handlers, and modern frameworks. 📌 1️⃣ this Keyword In JavaScript, this refers to the object that is executing the current function. const user = { name: "Developer", greet() { console.log(`Hello ${this.name}`) } } user.greet() Output Hello Developer Here, this refers to the user object because the method is called using user.greet(). ⚡ 2️⃣ call() – Execute a function with a specific context The call() method invokes a function immediately and allows us to set the value of this. function greet(){ console.log(`Hello ${this.name}`) } const user = { name: "Developer" } greet.call(user) We can also pass arguments: function greet(city){ console.log(`${this.name} from ${city}`) } const user = { name: "Developer" } greet.call(user, "Meerut") ⚡ 3️⃣ apply() – Similar to call but arguments are passed as an array function greet(city, country){ console.log(`${this.name} from ${city}, ${country}`) } const user = { name: "Developer" } greet.apply(user, ["Meerut", "India"]) ⚡ 4️⃣ bind() – Creates a new function with a fixed this Unlike call() and apply(), the bind() method does not execute the function immediately. Instead, it returns a new function with the specified this value. function greet(){ console.log(`Hello ${this.name}`) } const user = { name: "Developer" } const greetUser = greet.bind(user) greetUser() 💡 Understanding the difference • call() executes the function immediately and arguments are passed normally (comma separated). • apply() also executes the function immediately, but arguments are passed as an array. • bind() does not execute the function immediately. Instead, it returns a new function with the this value permanently bound, which can be executed later. ⚡ Why this concept matters Understanding function context is crucial for: • Reusing functions across objects • Controlling behavior of callbacks • Writing modular and maintainable code • Working effectively with event handlers and asynchronous code Mastering these JavaScript fundamentals helps developers build more predictable and scalable applications. #JavaScript #WebDevelopment #Programming #FrontendDevelopment #Coding #SoftwareDevelopment #DeveloperJourney
To view or add a comment, sign in
-
🚀 JavaScript - Array.prototype & Prototype Chaining If you’ve ever used map(), filter(), or push()… Have you ever wondered where they actually come from? 🤔 You’re already using one of the most powerful concepts in JavaScript 👇 👉 Prototype-based inheritance ⚡ What is Array.prototype? Every array you create is not just a simple object… 👉 It is internally linked to a hidden object called "Array.prototype" This object contains all the built-in methods available to arrays. Example: const arr = [1, 2, 3]; arr.push(4); arr.map(x => x * 2); 👉 These methods are NOT inside your array directly 👉 They come from Array.prototype Behind the Scenes console.log(arr.__proto__ === Array.prototype); // true 👉 This means: >>arr is connected to Array.prototype >>That’s why it can access all its methods 👉 __proto__ is a hidden property that exists in every JavaScript object. 👉 It points to the object’s prototype. const arr = [1, 2, 3]; console.log(arr.__proto__); // Array.prototype ⚡ Types of Methods in Array.prototype 🔸 A. Transformation Methods: Used to create new arrays arr.map(), arr.filter(), arr.reduce() 👉 Do NOT modify original array 🔸 B. Iteration Methods: Used to check or loop arr.forEach(), arr.find(), arr.some(), arr.every() 🔸 C. Modification Methods: Change the original array arr.push(), arr.pop(), arr.shift(), arr.unshift(), arr.splice() 🔸 D. Utility Methods: Helpful operations arr.includes(), arr.indexOf(), arr.slice(), arr.concat() ⚡What is Prototype Chaining? 👉 When you access a method/property, JavaScript searches step by step: arr → Array.prototype → Object.prototype → null This process is called "Prototype chaining". Example const arr = [1, 2, 3]; arr.toString(); 👉 toString() is not in array methods list, So JS checks: arr → Array.prototype → Object.prototype → null 👉 Found in Object.prototype ⚡Prototype Chain Visualization [1,2,3] ↓ Array.prototype ↓ Object.prototype ↓ null 👉 This chain is called prototype chaining ⚡Adding Custom Methods (Powerful but Risky) You can extend arrays like this: Array.prototype.custom = function () { return "Custom method!"; }; const arr = [1, 2]; console.log(arr.custom()); 👉 Arrays don’t own methods 👉 They inherit them from Array.prototype 👉 JavaScript uses prototype chaining to find them #JavaScript #WebDevelopment #Frontend #Coding #Developers #Programming #LearnJavaScript #100DaysOfCode
To view or add a comment, sign in
-
**🚀 I built a JavaScript Execution Visualizer — because understanding the Event Loop shouldn't require a PhD.** After spending way too long confused by async JavaScript, I decided to build a tool that makes it *visual*. **JS Visualizer** lets you paste any JavaScript code and watch it execute — step by step — with real-time animations showing exactly what's happening under the hood. **What it visualizes:** - 📦 **Call Stack** — watch execution contexts push and pop in real time - ⏱ **Web APIs** — see `setTimeout` and `fetch` handed off to the browser - ⚡ **Microtask Queue** — Promise callbacks, queued with priority - 🔄 **Task Queue** — macro tasks waiting their turn - ♾ **Event Loop** — animated ring showing which queue is being processed **The classic event loop puzzle — solved visually:** ``` console.log('1: Start'); // runs first setTimeout(callback, 0); // goes to Web APIs → Task Queue Promise.resolve().then(fn); // goes to Microtask Queue console.log('2: End'); // runs before both callbacks // Output order: 1 → 2 → Promise .then → setTimeout ``` Most developers *know* microtasks run before tasks — but watching it happen live makes it click in a completely different way. **Tech stack:** - Vanilla HTML / CSS / JavaScript (no frameworks needed) - [Acorn.js](https://lnkd.in/g7f4aC5Y) for AST parsing — the actual JS code you paste gets parsed into an AST and walked node-by-node - CodeMirror 5 for the editor with live line highlighting - 100% dark mode, production-quality design **Supports:** ✅ Synchronous function call stacks with closure variables ✅ `setTimeout` / `setInterval` → Web APIs → Task Queue ✅ `Promise.resolve().then()` → Microtask Queue ✅ `new Promise(executor)` with `resolve` / `reject` ✅ `queueMicrotask`, `fetch` ✅ `if/else`, `for`, `while`, `try/catch` ✅ Keyboard navigation (← →) This was a genuinely hard problem — building a safe AST-walking interpreter that accurately models the JavaScript event loop from scratch, without executing the code directly. If you're learning JavaScript async, teaching it, or just want to see the event loop in action — give it a try. https://lnkd.in/gWfdaUWM 💬 What JavaScript concept do you wish you had a visual tool for when you were learning? Drop it in the comments 👇 --- #JavaScript #WebDevelopment #EventLoop #AsyncJS #Programming #OpenSource #FrontendDevelopment #LearnToCode #DevTools #Coding
To view or add a comment, sign in
-
-
💻 Day 88 — Mastering JavaScript Objects Today's learning was focused on one of the most important foundations of JavaScript: Objects. Objects are everywhere in JS — from APIs to DOM elements, browser events, user data, configurations, classes, and much more. Understanding them deeply is crucial for becoming a strong JavaScript developer. 🎯 What I Learned / Practiced 🔹 Creating & Accessing Objects — Learned how to create objects with key–value pairs and practiced accessing values using dot notation; discovered that JavaScript handles duplicate keys by overriding earlier values with the latest one 🔹 Extracting Keys, Values & Entries — Practiced using Object.keys() to return all keys, Object.values() to return all values, and Object.entries() to return key–value pairs; these are extremely useful when iterating over objects or converting them into arrays 🔹 Updating & Deleting Object Properties — Learned that object properties can be updated anytime and unwanted keys can be removed using the delete operator 🔹 Understanding this Keyword — Explored how this works inside objects; inside an object method, this refers to the current object, making it possible to access its properties 🔹 Functions & Object Context (call, apply, bind) — Learned how to borrow object properties into standalone functions using call() to invoke the function with a given object, apply() (similar to call but accepts an array of arguments), and bind() to return a new function with fixed object context 🔹 JavaScript Quirks (Type Coercion) — Explored surprising JavaScript comparisons like false == [], false == '', and false == ![], which showed how loose equality (==) performs type coercion and can produce unexpected results 💡 Simple Example I created an object representing a user with properties like name and age. Then I used this inside a method to access those properties. I also practiced using call() to borrow a method from one object and use it with another object's data. This helped me understand how execution context works and how to control it when needed. 🌱 Reflection / Key Takeaways Today helped me strengthen my understanding of how objects store and manage data, context binding using this, call, apply, and bind, and JavaScript's unique type coercion behavior. These concepts form a strong base for upcoming topics like classes, prototypes, and advanced object manipulation. Objects are truly the foundation of modern JavaScript development. 🔗 Links GitHub:https://lnkd.in/gX8M3P4g Live Demo (Vercel):https://lnkd.in/gx9rBKYE 🙏 Thank you for the continuous guidance and support Codegnan | Uppugundla Sairam | Saketh Kallepu | Ambica Kiranmayee Bellamkonda #Day88 #FullStackDevelopment #FrontendDevelopment #JavaScript #Objects #WebDevelopment #LearningJourney
To view or add a comment, sign in
-
🚀 JavaScript Simplified Series — Day 20 Till now… you’ve learned JavaScript concepts. But here’s the real question 👇 👉 How does JavaScript actually interact with a website? How does a button click work? How does text change on screen? How does a form submit? This is where DOM comes in. 🔥 What is DOM? DOM stands for: 👉 Document Object Model Simple words me: DOM is a tree-like structure of your HTML page which JavaScript can read and modify. 🔹 Let’s Understand with a Real Example Imagine this HTML: <body> <h1>Hello</h1> <button>Click Me</button> </body> Browser ise internally convert karta hai: Document └── body ├── h1 └── button 👉 Ye pura structure hi DOM hai 🔹 Why DOM is Important? Without DOM: ❌ JavaScript kuch change nahi kar sakta ❌ Website static rahegi With DOM: ✅ Text change kar sakte ho ✅ Elements add/remove kar sakte ho ✅ Events handle kar sakte ho 🔹 Accessing DOM using JavaScript let heading = document.querySelector("h1") console.log(heading) 👉 JavaScript ne HTML element access kar liya 🔹 Changing Content let heading = document.querySelector("h1") heading.innerText = "Welcome to JavaScript" 👉 Screen par text change ho jayega 😎 🔹 Button Click Example let button = document.querySelector("button") button.addEventListener("click", function() { alert("Button Clicked!") }) 👉 User click kare → action trigger hota hai 🔥 Real Life Example Think of a website like a remote-controlled machine 🎮 HTML → structure CSS → design JavaScript (DOM) → control 👉 DOM is the bridge between JavaScript and HTML 🔥 Simple Summary DOM → HTML ka structure JavaScript → DOM ko control karta hai Result → Interactive website 💡 Programming Rule If you can control the DOM, you can control the entire website. If you want to learn JavaScript in a simple and practical way, you can follow these YouTube channels: • Rohit Negi •Hitesh Choudhary (Chai aur Code) 📌 Series Progress Day 1 → What is JavaScript Day 2 → Variables & Data Types Day 3 → Type Conversion & Operators Day 4 → Truthy & Falsy + Comparison Operators Day 5 → If Else + Switch + Ternary Day 6 → Loops Day 7 → Break + Continue + Nested Loops Day 8 → Functions Basics Day 9 → Arrow + Default + Rest Parameters Day 10 → Callback & Higher Order Functions Day 11 → Arrays Basics Day 12 → Array Methods Day 13 → Array Iteration Day 14 → Advanced Array Methods Day 15 → Objects Basics Day 16 → Object Methods + this Day 17 → Object Destructuring Day 18 → Spread & Rest Day 19 → Advanced Objects Day 20 → DOM Introduction Day 21 → Selecting Elements (Next Post) Follow for more 🚀 #JavaScriptSimplified #javascript #webdevelopment #coding #programming #learninpublic #100DaysOfCode #frontenddevelopment #devcommunity #codingjourney #softwaredeveloper #techcommunity #dailylearning #codeeveryday
To view or add a comment, sign in
-
🚀 JavaScript Event Loop “JavaScript is single-threaded…” 🧵 👉 Then how does it handle timers, API calls, promises, and user interactions so smoothly? What is the Event Loop? 👉 The Event Loop is a mechanism that continuously checks the call stack and task queues, and executes code in the correct order without blocking the main thread. 👉 It ensures JavaScript remains non-blocking and efficient. To Understand Event Loop, You Need 5 Core Pieces: 1️⃣ Call Stack 📚 The Call Stack is a data structure that keeps track of function execution in JavaScript. It follows the Last In, First Out (LIFO) principle. ⚙️ How It Works: >> When a function is called → it is pushed onto the stack >> When the function completes → it is popped off the stack >> The stack always runs one function at a time Example: function greet() { console.log("Hello"); } greet(); 👉 Goes into stack → executes → removed 2️⃣ Web APIs 🌐 👉 Provided by the browser (not JavaScript itself) Handles async operations like: setTimeout, fetch, DOM events.... 3️⃣ Callback Queue (Macrotask Queue) 📥: The Callback Queue (also called Task Queue) is a place where callback functions wait after completing asynchronous operations, until the Call Stack is ready to execute them. ⚙️ How It Works: >> Async function (like setTimeout) runs in background >> After completion → its callback goes to Callback Queue Event Loop checks: > If Call Stack is empty → moves callback to stack > If not → waits 👉 Any callback from async operations like timers, events, or I/O goes into the Callback Queue (except Promises, which go to Microtask Queue). 4️⃣ Microtask Queue ⚡: The Microtask Queue is a special queue in JavaScript that stores high-priority callbacks, which are executed before the Callback Queue. ⚙️How It Works: Execute all synchronous code (Call Stack) Check Microtask Queue Execute ALL microtasks Then move to Callback Queue 5️⃣ Event Loop 🔁 👉 Keeps checking: 👉 “Is the call stack empty?” If YES: >> Execute all microtasks >> Then execute macrotasks Example: console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); Output: Start End Promise Timeout 🚀 Key Takeaways: >> JS executes synchronous code first >> Then Microtasks (Promises) completely >> Then Callback Queue (setTimeout, events) >> Event Loop keeps checking and moving tasks #JavaScript #EventLoop #AsyncJavaScript #WebDevelopment #Frontend #Coding #Developers #Programming #LearnJavaScript #100DaysOfCode
To view or add a comment, sign in
-
-
Small JavaScript bugs keep escaping to production and breaking critical user flows. Debugging inconsistent runtime behavior steals time from feature delivery. ────────────────────────────── Proxy and Reflect API Guide with Examples This tutorial provides an advanced understanding of the Proxy and Reflect APIs in JavaScript, including practical examples, common use cases, and architectural considerations for enterprise applications. hashtag#javascript hashtag#proxy hashtag#reflect hashtag#api hashtag#advanced hashtag#architecture ────────────────────────────── How to Use Proxy and Reflect API Quickly? The fastest way to utilize the Proxy and Reflect APIs is by creating a simple proxy object that wraps an existing object. You can easily intercept operations like property access, assignment, and function calls. Here's a quick example of using Proxy with a handler to log property accesses: const target = { message: 'Hello, World!' }; const handler = { get: function(obj, prop) { console.log(Property ${prop} was accessed.); return obj[prop]; } }; const proxy = new Proxy(target, handler); console.log(proxy.message); // Logs: Property message was accessed. How to Proxy and Reflect API in Detail? The Proxy object allows you to define custom behavior for fundamental operations (e.g., property lookup, assignment, enumeration, function invocation, etc.). It is basically a wrapper around another object (the target) and intercepts operations performed on that object. The Reflect API complements Proxy by providing methods to perform operations on objects. It simplifies the work of the Proxy by offering methods that mirror the default behavior of JavaScript operations. For example, Reflect.get() can be used to access a property while respecting the Proxy's traps. Let's examine a detailed example where we create a Proxy to track user activity in an application: const user = { name: 'John Doe', age: 30, }; const handler = { get(target, prop) { if (prop in target) { console.log(Getting ${prop}: ${target[prop]}); return Reflect.get(target, prop); } else { console.log(Property ${prop} does not exist.); return undefined; } }, set(target, prop, value) { console.log(Setting ${prop} to ${value}); return Reflect.set(target, prop, value); } }; const proxy = new Proxy(user, handler); proxy.name; // Logs: Getting name: John Doe proxy.age = 31; // Logs: Setting age to 31 proxy.gender; // Logs: Property gender does not exist. In this example, we see how the get and set traps are defined. Each time a property is accessed or modified, it logs the action. The use of Reflect ensures that the original target object's behavior is preserved. What is Proxy and Reflect API? The Proxy API was introduced in ECMAScript 2015 (ES6) to provide a powerful way to create flexible and dynamic objects. A Proxy can redefine fundamental operations—lik
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