Most developers think inheritance in JavaScript works like traditional OOP. It doesn’t. And that confusion leads to messy, over-engineered code. JavaScript uses prototypal inheritance — not classical inheritance. 👉 Objects inherit directly from other objects. 💡 There are 3 main ways inheritance works in JavaScript: 🔹 1. Prototypal Inheritance (Core Concept) const animal = { speak() { console.log("Makes a sound"); } }; const dog = Object.create(animal); dog.bark = function () { console.log("Bark"); }; dog.speak(); // inherited dog.bark(); // own method ✔ Simple ✔ Flexible ✔ Native to JS 🔹 2. Constructor Function Inheritance function Animal(name) { this.name = name; } Animal.prototype.speak = function () { console.log(this.name + " makes noise"); }; function Dog(name) { Animal.call(this, name); // inherit properties } Dog.prototype = Object.create(Animal.prototype); const d = new Dog("Tommy"); d.speak(); ✔ More structured ✔ Used in older codebases 🔹 3. Class-based Inheritance (ES6) class Animal { constructor(name) { this.name = name; } speak() { console.log(this.name + " makes noise"); } } class Dog extends Animal { bark() { console.log("Bark"); } } const dog = new Dog("Rocky"); dog.speak(); dog.bark(); ✔ Cleaner syntax ✔ Easier to read ❗ Still uses prototypes under the hood ⚡ The truth most people miss: Even with classes… 👉 JavaScript is STILL prototype-based. Classes are just syntactic sugar. 🧠 The real upgrade: Stop thinking: “Which syntax should I use?” Start thinking: “How does inheritance actually work under the hood?” Because once you understand prototypes… You don’t just write code— you understand it. What confused you more in JavaScript—closures, promises, or prototypes? 👇 #JavaScript #WebDevelopment #Programming #Frontend #Coding #SoftwareEngineering
JavaScript Inheritance: Prototypal vs Classical vs ES6
More Relevant Posts
-
🚀 JavaScript Hoisting — what it actually means (with a simple mental model) Most people say: “Variables and functions are moved to the top". Even the educators on youtube (some of them) are teaching that and even I remember answering that in my first interview call. That’s not wrong… but it’s also not the full picture. Then Priya what’s really happening? JavaScript doesn’t “move” your code. Instead, during execution, it runs in two phases: 1️⃣ Creation Phase Memory is allocated Variables → initialised as undefined Functions → fully stored in memory 2️⃣ Execution Phase Code runs line by line Values are assigned 🎨 Think of it like this: Before running your code, JavaScript prepares a “memory box” 📦 Creation Phase: a → undefined sayHi → function() { ... } Execution Phase: console.log(a) → undefined a = 10 🔍 Example 1 (var) console.log(a); // undefined var a = 10; 👉 Why? Because JS already did: var a = undefined; ⚡ Example 2 (function) sayHi(); // Works! function sayHi() { console.log("Hello"); } 👉 Functions are fully hoisted with their definition. 🚫 Example 3 (let / const) console.log(a); // ❌ ReferenceError let a = 10; 👉 They are hoisted too… But stuck in the Temporal Dead Zone (TDZ) until initialised. 🧩 Simple rule to remember: var → hoisted + undefined function → hoisted completely let/const → hoisted but unusable before declaration 💬 Ever seen undefined and wondered why? 👉 That’s hoisting working behind the scenes. #javascript #webdevelopment #frontend #reactjs #programming #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Day 8 / 30 - JavaScript Coding Practice Today’s challenge: Rebuilding Array.filter() without using the built-in method 👀 Problem: Given an integer array arr and a filtering function fn, return a filtered array filteredArr. The fn function takes one or two arguments: arr[i] - number from the arr i - index of arr[i] filteredArr should only contain the elements from the arr for which the expression fn(arr[i], i) evaluates to a truthy value. A truthy value is a value where Boolean(value) returns true. Please solve it without the built-in Array.filter method. Example 1: Input: arr = [0,10,20,30], fn = function greaterThan10(n) { return n > 10; } Output: [20,30] Explanation: const newArray = filter(arr, fn); // [20, 30] The function filters out values that are not greater than 10 Example 2: Input: arr = [1,2,3], fn = function firstIndex(n, i) { return i === 0; } Output: [1] Explanation: fn can also accept the index of each element In this case, the function removes elements not at index 0 Example 3: Input: arr = [-2,-1,0,1,2], fn = function plusOne(n) { return n + 1 } Output: [-2,0,1,2] Explanation: Falsey values such as 0 should be filtered out Solution: var filter = function (arr, fn) { let formattedArr = []; for (let i = 0; i < arr.length; i++) { if (fn(arr[i], i)) { formattedArr.push(arr[i]); } } return formattedArr; }; #JavaScript #DSA #CodingPractice #100DaysOfCode #FrontendDevelopment #ProblemSolving
To view or add a comment, sign in
-
-
Have you ever felt overwhelmed by JavaScript objects? The good news is that methods like Object.keys(), Object.values(), and Object.entries() can simplify how we interact with them. Which one do you find yourself using the most? ────────────────────────────── Demystifying Object.keys(), Object.values(), and Object.entries() Unlock the power of object methods in JavaScript with these simple techniques. #javascript #es6 #programming ────────────────────────────── Key Rules • Object.keys(obj) returns an array of the object's own property names. • Object.values(obj) returns an array of the object's own property values. • Object.entries(obj) returns an array of the object's own property [key, value] pairs. 💡 Try This const person = { name: 'Alice', age: 30, city: 'Wonderland' }; console.log(Object.keys(person)); // ['name', 'age', 'city'] console.log(Object.values(person)); // ['Alice', 30, 'Wonderland'] console.log(Object.entries(person)); // [['name', 'Alice'], ['age', 30], ['city', 'Wonderland']] ❓ Quick Quiz Q: What does Object.entries() return? A: An array of [key, value] pairs from the object. 🔑 Key Takeaway Using these methods can drastically improve your code's readability and efficiency! ────────────────────────────── Small JavaScript bugs keep escaping to production and breaking critical user flows. Debugging inconsistent runtime behavior steals time from feature delivery.
To view or add a comment, sign in
-
Just wrote a blog on the "new" keyword in JS Under the hood, new follows a precise process: • Creates a new empty object • Links it to the constructor’s prototype • Binds this to that object • Executes the constructor function • Returns the final instance If you're learning JavaScript or revisiting fundamentals, this will sharpen your understanding 👇 https://lnkd.in/gEitS7KJ #JavaScript #WebDevelopment #Frontend #Programming #Coding #LearnInPublic #Developers #SoftwareEngineering
To view or add a comment, sign in
-
Wrote a new blog on Destructuring in JavaScript. One of those features that seems small at first, but has a huge impact on code quality. Covering: • What destructuring actually means • Array vs object destructuring • Default values (and why they matter) • Before vs after comparisons • Writing cleaner, more readable code https://lnkd.in/g2y6rmnt Hitesh Choudhary Chai Aur Code Piyush Garg Akash Kadlag Jay Kadlag Nikhil Rathore #javascript #webdevelopment #frontend #coding #programming #developers #learninpublic #100daysofcode
To view or add a comment, sign in
-
🚀 Callbacks vs Promises in JavaScript — Why Modern Code Avoids Callback Hell One of the biggest challenges in JavaScript is handling asynchronous operations such as API calls, file reading, or timers. For years, developers relied on Callbacks to execute code after an async task finished. But as applications grew, this approach introduced a serious problem: Callback Hell. 🕸️ Callback Hell problems • Deeply nested code (Pyramid of Doom) • Harder debugging and error handling • Poor readability and maintainability Example structure developers often struggled with: Callback → Callback → Callback → Callback 💎 Promises (ES6) changed the game A Promise represents the eventual result of an asynchronous operation. A Promise can be in one of three states: • Pending • Fulfilled • Rejected Promises improve asynchronous code by providing: ✔ Cleaner structure through Promise chaining ✔ Centralized error handling with .catch() ✔ Better readability and maintainability ⚡ Technical Advantage (Under the hood) Promises are processed through the Microtask Queue inside the JavaScript Event Loop. This means they are executed with higher priority than traditional callbacks scheduled in the task queue. ⚡ Powerful Promise utilities Modern JavaScript also provides powerful Promise tools: • Promise.all() → run multiple async operations in parallel • Promise.race() → resolve with the fastest result These utilities help improve performance and concurrency in real-world applications. 🌟 And then came async/await async/await is not a replacement for Promises. It is simply syntactic sugar built on top of Promises that allows asynchronous code to look like synchronous code — improving readability and clean architecture. 💡 Quick Summary Callback → Function executed after a task finishes Promise → Object representing the future completion or failure of an async operation 💬 Question for developers When dealing with multiple dependent API calls… Do you still use callbacks, or do you prefer the clarity of Promises / async-await? #javascript #webdevelopment #frontend #softwareengineering #coding #cleancode
To view or add a comment, sign in
-
-
🚀 Master JavaScript Under the Hood! A deep dive into core JS concepts to level up your engineering skills: 📦 Execution Context & Engine: Everything in JavaScript happens inside an Execution Context, containing a memory and code component. JS is a synchronous, single-threaded language executed efficiently by engines using a Call Stack and Just-In-Time compilation. ✨ Hoisting & TDZ: During memory creation, variables and functions are allocated memory before execution. let and const reside in a Temporal Dead Zone until initialized, while var receives an undefined placeholder. 🔒 Lexical Scope & Closures: A closure is a function bundled with its lexical environment. This environment consists of local memory and a reference to the parent's lexical environment, forming the Scope Chain. 🔄 Event Loop & Async: The Event Loop continuously monitors the Call Stack and task queues. Promise callbacks go to the higher-priority Microtask Queue, while setTimeout goes to the standard Callback Queue. setTimeout only guarantees a minimum delay since it waits for the Call Stack to empty. 🛠 First-Class Functions: Functions are "First-Class Citizens" because they can be passed as arguments or returned as values. This enables Higher-Order Functions like map, filter, and reduce. 🤝 Promises: A Promise is an object representing the eventual completion of an asynchronous operation, preventing "Callback Hell" and "Inversion of Control". For parallel tasks: Promise.all fails fast, Promise.allSettled safely waits for all, Promise.race returns the first settled result, and Promise.any seeks the first success. 🎯 The this Keyword: The value of this depends on how a function is called. Globally, it points to the global object like window. In non-strict mode, "this substitution" replaces undefined with the global object. Arrow functions lack their own this binding, retaining the value of their enclosing lexical context. #JavaScript #WebDev #Frontend #SoftwareEngineering #Coding
To view or add a comment, sign in
-
"JS Fundamentals Series #5: Event Loop & Async Programming" Ever wondered why promises resolve before setTimeout, even with zero delay? That's the magic of the Event Loop - The mechanism that makes JavaScript handle asynchronous tasks while staying single-threaded. 👉 Event Loop: Continuously checks the call stack and queues, moving tasks into execution when the stack is clear. 👉 Call Stack, Callback Queue, Microtask Queue: - Call Stack - Executes synchronous code line by line. - Microtask Queue - Holds promises and async/await tasks (executed before callbacks) - Callback Queue - Holds taste like setTimeout and event handlers. 🔹 Explanation - The event loop ensures non-blocking execution. - Promises (microtasks) always run before callbacks (macrotasks). - This explains why async code often behaves differently than expected. 🔹 Example console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); Output: Start End Promise Timeout 🔹 Analogy Think of it like a restaurant: - Call Stack: Chef cooking immediate orders. - Microtask Queue (Promises): VIP priority orders. - Callback Queue (setTimeout): Regular orders waiting in line. 🔹 Why It Matters - Explains async behavior that confuses beginners. - Helps debug performance issues. - Essential for mastering async/await and modern frameworks like React. 💡 Takeaway: Understanding the Event Loop is key to mastering asynchronous programming in JavaScript. #JavaScript #WebDevelopment #AsyncProgramming #Frontend #ReactJS #CodingTips #DeveloperCommunity #NamasteJS #LearningJourney #TechExplained #CareerGrowth "Event Loop in action: Call Stack → Microtask Queue → Callback Queue 👇"
To view or add a comment, sign in
-
-
⚡ JavaScript async code still confusing? You’re not alone. Most beginners learn both: 👉 Promises 👉 async/await …but don’t know when to use which. Let’s simplify it 👇 🔗 Promises → Chain multiple async operations → Good for handling complex flows ✨ async/await → Cleaner, more readable code → Feels like synchronous programming Example mindset: 👉 Promises = “then().then().catch()” chain 👉 async/await = “write async code like normal code” So which one should you use? 💡 Use async/await when: ✔ You want clean and readable code ✔ You’re writing simple to moderate async logic 💡 Use Promises when: ✔ You need parallel execution (e.g., Promise.all) ✔ You’re handling complex chaining scenarios I wrote a simple guide explaining: ✔ Key differences ✔ Real use cases ✔ Best practices developers actually use 🔗 Read here: https://lnkd.in/g6D2_vcg 🚀 Pro tip: Master async/await first — then understand Promises deeply. Comment "JS" and I’ll share async coding interview questions 👇 #JavaScript #WebDevelopment #Frontend #Coding #Developers #AsyncAwait #Programming
To view or add a comment, sign in
-
Most developers use JavaScript… but very few actually understand how it works under the hood. One concept that completely changed how I debug async code 👇 🚀 Event Loop (in DOM / Browser context) JavaScript is single-threaded. That means — one task at a time. But then how does this work? setTimeout API calls (fetch) button clicks Promises All happening “simultaneously”? 👉 The answer: Event Loop 🧠 Mental Model (Simple but Powerful) There are 3 main layers: Call Stack → where synchronous code runs Microtask Queue → Promises (high priority) Callback Queue → setTimeout, DOM events ⚡ Execution Priority Call Stack → Microtasks → Callback Queue 🔥 Example: console.log("1"); setTimeout(() => console.log("2"), 0); Promise.resolve().then(() => console.log("3")); console.log("4"); 👉 Output: 1 4 3 2 💡 Key Insights: setTimeout(0) is NOT immediate Promises always run before timers Heavy sync code blocks everything (including UI) Infinite microtasks = UI freeze ⚠️ Reality Check: If you don’t understand the event loop: Debugging async bugs becomes guesswork Performance issues become invisible Race conditions become nightmares ✅ Verdict: Must-know concept Not optional. Not “nice to have”. This is the foundation of: React behavior API handling Performance optimization If you're learning JavaScript seriously, don’t skip internals. Because that’s where average developers stop — and strong engineers begin.
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