🤔 Preparing for your next JavaScript interview? Today, we're tackling one of the most crucial and misunderstood concepts in JavaScript: The Event Loop. JavaScript is single-threaded, meaning it has only one "Call Stack" and can only do one thing at a time. So, how does it handle time-consuming operations like API calls (fetch) or timers (setTimeout) without freezing the entire browser? The answer is that the JavaScript engine doesn't work alone. It gets help from the browser environment and a manager called the Event Loop. Here’s the complete system in a nutshell: 1. The Call Stack: This is where your JavaScript code is executed, one line at a time. 2. Web APIs: These are features provided by the browser (not the JS engine). When your code calls a slow operation like setTimeout, the JS engine hands it off to the Web API to handle in the background. The engine then immediately moves on to the next line of code, keeping the Call Stack free. 3.The Callback Queue (or Task Queue): Once the Web API finishes its job (the timer completes, the data arrives), it doesn't interrupt your code. Instead, it places the function you provided (the "callback") into this waiting line. This brings us to the final, critical piece. How does the function get from the waiting line back into the main code to be run? ✅ Enter the Event Loop: The Event Loop is a simple, constantly running process with one golden rule: "If the Call Stack is empty, take the first item from the Callback Queue and push it onto the Call Stack to be executed." ``` console.log('First'); setTimeout(() => { console.log('Second'); }, 0); console.log('Third'); // Output: First, Third, Second ``` Why this order? 1. `console.log('First')` goes to the Call Stack and runs. 2. `setTimeout` is handed to a Web API. JavaScript immediately continues. 3. `console.log('Third')` goes to the Call Stack and runs. 4. The `Call Stack` is now empty. 5. In the background, the timer finishes instantly (0ms) and places its callback `() => console.log('Second')` into the Callback Queue. 6. The Event Loop sees the Call Stack is empty, takes the callback from the queue, and pushes it onto the stack to run. This system is what makes JavaScript "non-blocking." The Event Loop ensures that slow tasks wait their turn without ever freezing the user interface. #javascript #eventloop #asynchronousjavascript #webdevelopment #frontenddevelopment #backenddevelopment #nodejs #v8engine #callstack #microtasks
Understanding JavaScript's Event Loop for Efficient Coding
More Relevant Posts
-
Here is Top JavaScript #interview Questions. 1. What is the difference between var, let, and const in JavaScript? 2. What are closures in JavaScript, and how do they work? 3. What is the this keyword in JavaScript, and how does it behave in different contexts? 4. What is a JavaScript promise, and how does it handle asynchronous code? 5. What is the event loop, and how does JavaScript handle asynchronous operations? 6. What is hoisting in JavaScript, and how does it work? 7. What are JavaScript data types, and how do you check the type of a variable? 8. What is the difference between null and undefined in JavaScript? 9. What is a callback function, and how is it used? 10. How do you manage errors in JavaScript? 11. What is the difference between setTimeout() and setInterval()? 12. How do JavaScript promises work, and what is the then() method? 13. What is async/await, and how does it simplify asynchronous code in JavaScript? 14. What are the advantages of using async functions over callbacks? 15. How do you handle multiple promises simultaneously? 16. What are higher-order functions in JavaScript, and can you provide an example? 17. What is destructuring in JavaScript, and how is it useful? 18. What are template literals in JavaScript, and how do they work? 19. How does the spread operator work in JavaScript? 20. What is the rest parameter in JavaScript, and how does it differ from the arguments object? 21. What is the difference between an object and an array in JavaScript? 22. How do you clone an object or array in JavaScript? 23. What are object methods like Object.keys(), Object.values(), and Object.entries()? 24. How does the map() method work in JavaScript, and when would you use it? 25. What is the difference between map() and forEach() in JavaScript? 26. What is event delegation in JavaScript, and why is it useful? 27. What are JavaScript modules, and how do you import/export them? 28. What is the prototype chain in JavaScript, and how does inheritance work? 29. What is bind(), call(), and apply() in JavaScript, and when do you use them? 30. How does JavaScript handle equality comparisons with == and ===? 31. What is the Document Object Model (DOM), and how does JavaScript interact with it? 32. How do you prevent default actions and stop event propagation in JavaScript? 33. What is the difference between synchronous and asynchronous code in JavaScript? 34. What is the difference between an event object and a custom event in JavaScript? 35. How do you optimize performance in JavaScript applications? 💬 Comment if you'd like more interview preparation resources #javascript #freshers #interview #js #frontend #webdevlopment #linkedin #frontend
To view or add a comment, sign in
-
Top Javascript #interview Questions 1. What is the difference between var, let, and const in JavaScript? 2. What are closures in JavaScript, and how do they work? 3. What is the this keyword in JavaScript, and how does it behave in different contexts? 4. What is a JavaScript promise, and how does it handle asynchronous code? 5. What is the event loop, and how does JavaScript handle asynchronous operations? 6. What is hoisting in JavaScript, and how does it work? 7. What are JavaScript data types, and how do you check the type of a variable? 8. What is the difference between null and undefined in JavaScript? 9. What is a callback function, and how is it used? 10. How do you manage errors in JavaScript? 11. What is the difference between setTimeout() and setInterval()? 12. How do JavaScript promises work, and what is the then() method? 13. What is async/await, and how does it simplify asynchronous code in JavaScript? 14. What are the advantages of using async functions over callbacks? 15. How do you handle multiple promises simultaneously? 16. What are higher-order functions in JavaScript, and can you provide an example? 17. What is destructuring in JavaScript, and how is it useful? 18. What are template literals in JavaScript, and how do they work? 19. How does the spread operator work in JavaScript? 20. What is the rest parameter in JavaScript, and how does it differ from the arguments object? 21. What is the difference between an object and an array in JavaScript? 22. How do you clone an object or array in JavaScript? 23. What are object methods like Object.keys(), Object.values(), and Object.entries()? 24. How does the map() method work in JavaScript, and when would you use it? 25. What is the difference between map() and forEach() in JavaScript? 26. What is event delegation in JavaScript, and why is it useful? 27. What are JavaScript modules, and how do you import/export them? 28. What is the prototype chain in JavaScript, and how does inheritance work? 29. What is bind(), call(), and apply() in JavaScript, and when do you use them? 30. How does JavaScript handle equality comparisons with == and ===? 31. What is the Document Object Model (DOM), and how does JavaScript interact with it? 32. How do you prevent default actions and stop event propagation in JavaScript? 33. What is the difference between synchronous and asynchronous code in JavaScript? 34. What is the difference between an event object and a custom event in JavaScript? 𝗦𝘁𝗮𝗿𝘁 𝘀𝗺𝗮𝗹𝗹 → 𝗕𝘂𝗶𝗹𝗱 → 𝗛𝗼𝗼𝗸 → 𝗙𝗲𝘁𝗰𝗵 → 𝗦𝘁𝘆𝗹𝗲 → 𝗧𝗲𝘀𝘁 → 𝗗𝗲𝗽𝗹𝗼𝘆. Follow us youtube:https://lnkd.in/gxf3T449 instragram:https://lnkd.in/g5jfDRxy #ReactJS #ReactHooks #ReactDeveloper #ReactTips #ReactCommunity #FrontendDevelopment #WebDevelopment #JavaScript #JSX #TypeScript #CodingLife #DevTips #TechCommunity #LearnToCode #javascript #interview2025 #freshers #frontend #learnandgrow #webdevlopment #fundametals
To view or add a comment, sign in
-
Top Javascript #interview Questions 1. What is the difference between var, let, and const in JavaScript? 2. What are closures in JavaScript, and how do they work? 3. What is the this keyword in JavaScript, and how does it behave in different contexts? 4. What is a JavaScript promise, and how does it handle asynchronous code? 5. What is the event loop, and how does JavaScript handle asynchronous operations? 6. What is hoisting in JavaScript, and how does it work? 7. What are JavaScript data types, and how do you check the type of a variable? 8. What is the difference between null and undefined in JavaScript? 9. What is a callback function, and how is it used? 10. How do you manage errors in JavaScript? 11. What is the difference between setTimeout() and setInterval()? 12. How do JavaScript promises work, and what is the then() method? 13. What is async/await, and how does it simplify asynchronous code in JavaScript? 14. What are the advantages of using async functions over callbacks? 15. How do you handle multiple promises simultaneously? 16. What are higher-order functions in JavaScript, and can you provide an example? 17. What is destructuring in JavaScript, and how is it useful? 18. What are template literals in JavaScript, and how do they work? 19. How does the spread operator work in JavaScript? 20. What is the rest parameter in JavaScript, and how does it differ from the arguments object? 21. What is the difference between an object and an array in JavaScript? 22. How do you clone an object or array in JavaScript? 23. What are object methods like Object.keys(), Object.values(), and Object.entries()? 24. How does the map() method work in JavaScript, and when would you use it? 25. What is the difference between map() and forEach() in JavaScript? 26. What is event delegation in JavaScript, and why is it useful? 27. What are JavaScript modules, and how do you import/export them? 28. What is the prototype chain in JavaScript, and how does inheritance work? 29. What is bind(), call(), and apply() in JavaScript, and when do you use them? 30. How does JavaScript handle equality comparisons with == and ===? 31. What is the Document Object Model (DOM), and how does JavaScript interact with it? 32. How do you prevent default actions and stop event propagation in JavaScript? 33. What is the difference between synchronous and asynchronous code in JavaScript? 34. What is the difference between an event object and a custom event in JavaScript? 35. How do you optimize performance in JavaScript applications? Follow Alpna P. for more related content! 🤔 Having Doubts in technical journey? 🚀 Book 1:1 session with me : https://lnkd.in/gQfXYuQm 🚀 Subscribe and stay up to date: https://lnkd.in/dGE5gxTy 🚀 Get Complete React JS Interview Q&A Here: https://lnkd.in/d5Y2ku23 🚀 Get Complete JavaScript Interview Q&A Here: https://lnkd.in/d8umA-53 #javascript #freshers #interview #js #frontend #webdevlopment #linkedin #frontend
To view or add a comment, sign in
-
🚨 I recently went through a JavaScript interview and they asked some very tricky questions. Honestly, these were not the usual “What is closure?” or “What is hoisting?” questions. They were designed to test how deeply you understand JavaScript execution, async behavior, and edge cases. If you’re preparing for Frontend / React interviews, don’t miss these questions. 👇 🧠 1️⃣ Predict the Output console.log([] + []); console.log([] + {}); console.log({} + []); console.log({} + {}); What exactly gets printed and why does JavaScript behave like this? ⚡ 2️⃣ Event Loop Deep Dive console.log("start"); setTimeout(() => console.log("timeout")); Promise.resolve().then(() => console.log("promise")); queueMicrotask(() => console.log("microtask")); console.log("end"); 👉 What is the exact output order? 🔥 3️⃣ Closures + Loop Trap for (var i = 0; i < 3; i++) { setTimeout(() => { console.log(i); }, 100); } What will be printed and why does this happen? 🧩 4️⃣ this Binding Confusion const obj = { value: 10, getValue() { return this.value; } }; const getValue = obj.getValue; console.log(getValue()); What will this print? ⚠️ 5️⃣ Object Reference Trap const a = { name: "JS" }; const b = a; b.name = "React"; console.log(a.name); Why does this happen? 🧪 6️⃣ Array Mutation Trick const arr = [1,2,3]; arr[10] = 99; console.log(arr.length); console.log(arr); What does the array actually look like? 🧠 7️⃣ Destructuring Edge Case const obj = { a: 1, b: 2 }; const { a, ...rest } = obj; rest.b = 5; console.log(obj.b); Does the original object change? ⚡ 8️⃣ Promise Chain Trap Promise.resolve(1) .then(x => x + 1) .then(x => { throw new Error("boom"); }) .catch(() => 10) .then(x => console.log(x)); What is the final output? 🔥 9️⃣ typeof Weirdness console.log(typeof NaN); console.log(typeof null); console.log(typeof []); Why do these results exist in JavaScript? 🧨 🔟 Implicit Type Coercion console.log("5" - 3); console.log("5" + 3); console.log(true + false); console.log([] == false); Explain how JavaScript converts the types internally. 💡 Principal Engineer Advice In interviews, they’re not testing if you memorized JavaScript. They are testing if you understand: ⚡ Execution Context ⚡ Event Loop ⚡ Closures ⚡ Type Coercion ⚡ Object References Master these and JavaScript interviews become much easier. 🔥 I’ll keep posting tricky Frontend / React interview questions daily to help juniors crack interviews. #javascript #frontend #reactjs #webdevelopment #frontendengineer #codinginterview
To view or add a comment, sign in
-
-
Top JavaScript #interview #Questions #Day34 1. What is the difference between var, let, and const in JavaScript? 2. What are closures in JavaScript, and how do they work? 3. What is the this keyword in JavaScript, and how does it behave in different contexts? 4. What is a JavaScript promise, and how does it handle asynchronous code? 5. What is the event loop, and how does JavaScript handle asynchronous operations? 6. What is hoisting in JavaScript, and how does it work? 7. What are JavaScript data types, and how do you check the type of a variable? 8. What is the difference between null and undefined in JavaScript? 9. What is a callback function, and how is it used? 10. How do you manage errors in JavaScript? 11. What is the difference between setTimeout() and setInterval()? 12. How do JavaScript promises work, and what is the then() method? 13. What is async/await, and how does it simplify asynchronous code in JavaScript? 14. What are the advantages of using async functions over callbacks? 15. How do you handle multiple promises simultaneously? 16. What are higher-order functions in JavaScript, and can you provide an example? 17. What is destructuring in JavaScript, and how is it useful? 18. What are template literals in JavaScript, and how do they work? 19. How does the spread operator work in JavaScript? 20. What is the rest parameter in JavaScript, and how does it differ from the arguments object? 21. What is the difference between an object and an array in JavaScript? 22. How do you clone an object or array in JavaScript? 23. What are object methods like Object.keys(), Object.values(), and Object.entries()? 24. How does the map() method work in JavaScript, and when would you use it? 25. What is the difference between map() and forEach() in JavaScript? 26. What is event delegation in JavaScript, and why is it useful? 27. What are JavaScript modules, and how do you import/export them? 28. What is the prototype chain in JavaScript, and how does inheritance work? 29. What is bind(), call(), and apply() in JavaScript, and when do you use them? 30. How does JavaScript handle equality comparisons with == and ===? 31. What is the Document Object Model (DOM), and how does JavaScript interact with it? 32. How do you prevent default actions and stop event propagation in JavaScript? 33. What is the difference between synchronous and asynchronous code in JavaScript? 34. What is the difference between an event object and a custom event in JavaScript? 35. How do you optimize performance in JavaScript applications? Follow Arun Dubey for more related content! 🤔 Having Doubts in technical journey? #javascript #freshers #interview #js #frontend #webdevlopment #linkedin #frontend
To view or add a comment, sign in
-
🚀 JavaScript "this" Explained Simply (Frontend Developer Must-Know) If you’re learning JavaScript, working with React, or preparing for frontend interviews, understanding the "this" keyword is non-negotiable. Yet it’s still one of the most misunderstood concepts in JavaScript. Let’s simplify it. ------------------------------------------------- 🔎 What is "this" in JavaScript? In JavaScript, this refers to the execution context of a function. And here’s the most important rule: 👉 "this" is NOT determined by where a function is written. 👉 It is determined by how the function is invoked. That one sentence changes everything. ------------------------------------------------- 🧠 The 4 JavaScript "this" Binding Rules (In Order of Priority) Every time a function runs, JavaScript determines this using a strict hierarchy. Understanding this hierarchy will instantly level up your JavaScript fundamentals. 1️⃣ Default Binding : When a function is called normally, without an owning object, this falls back to the global context (or becomes undefined in strict mode). 2️⃣ Implicit Binding : When a function is called as a method of an object, this refers to the object before the dot. 3️⃣ Explicit Binding : JavaScript allows you to manually control this using built-in methods that explicitly define the execution context. 4️⃣ new Binding (Highest Priority) : When a function is invoked using the new keyword, JavaScript creates a brand-new object and binds this to it. And here’s the advanced insight: 🔥 new overrides all other binding rules. Even if you try to manually control this, new wins. ⚠️ Arrow Functions Change the Game Arrow functions do not have their own this. Instead, they inherit this from their surrounding scope. This is why mixing regular functions and arrow functions without understanding the difference can lead to subtle bugs — especially in React applications. 🎯 Why Understanding "this" Is Important Mastering "this" helps you: ✅ Debug faster ✅ Write better React components ✅ Understand OOP in JavaScript ✅ Pass senior frontend interviews ✅ Avoid subtle production bugs 💡 The Ultimate Mental Model JavaScript decides this using "this" priority: new > explicit > implicit > default If you remember this order, you’ll rarely get confused. If you're a frontend developer serious about mastering JavaScript fundamentals, understanding this is non-negotiable. Save this post for later 📌 Share it with your dev friends 👨💻 #JavaScript #Frontend #ReactJS #WebDevelopment #Programming #SoftwareEngineering
To view or add a comment, sign in
-
-
here's some important JavaScript questions to crack interviews 𝟭. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝘁𝗵𝗶𝘀 𝗸𝗲𝘆𝘄𝗼𝗿𝗱? - Refers to the object that is currently executing the function - In global scope, this is the window object (in browsers) - Arrow functions do not have their own this 𝟮. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗣𝗿𝗼𝘁𝗼𝘁𝘆𝗽𝗮𝗹 𝗜𝗻𝗵𝗲𝗿𝗶𝘁𝗮𝗻𝗰𝗲? - JS objects inherit properties and methods from other objects via a prototype chain - Every object has a hidden __proto__ property pointing to its prototype - ES6 class syntax is just cleaner syntax over prototypal inheritance 𝟯. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝘁𝗵𝗲 𝗦𝗽𝗿𝗲𝗮𝗱 𝗮𝗻𝗱 𝗥𝗲𝘀𝘁 𝗢𝗽𝗲𝗿𝗮𝘁𝗼𝗿 (...)? - Spread expands an array or object: const newArr = [...arr, 4, 5] - Rest collects remaining arguments into an array: function fn(a, ...rest) {} - Same syntax, different context position determines behavior - Great for copying arrays/objects without mutation 𝟰. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗗𝗲𝘀𝘁𝗿𝘂𝗰𝘁𝘂𝗿𝗶𝗻𝗴? - Extract values from arrays or objects into variables cleanly - Array: const [first, second] = [1, 2] - Object: const { name, age } = user - Supports default values: const { name = 'Guest' } = user 𝟱. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗘𝘃𝗲𝗻𝘁 𝗗𝗲𝗹𝗲𝗴𝗮𝘁𝗶𝗼𝗻? - Instead of adding listeners to each child element, add one listener to the parent - Uses event bubbling events travel up the DOM tree - More memory efficient for large lists or dynamic content - Check event.target inside the handler to identify which child was clicked 𝟲. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝘁𝗵𝗲 𝗱𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝗰𝗲 𝗯𝗲𝘁𝘄𝗲𝗲𝗻 𝗰𝗮𝗹𝗹(), 𝗮𝗽𝗽𝗹𝘆()? - All three explicitly set the value of this - call() invokes immediately, passes args one by one - apply() invokes immediately, passes args as an array 𝟳. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗠𝗲𝗺𝗼𝗶𝘇𝗮𝘁𝗶𝗼𝗻? - Caching the result of a function call so it doesn't recompute for the same input - Improves performance for expensive or repeated operations - Commonly implemented using closures and objects/Maps 𝟴. 𝗪𝗵𝗮𝘁 𝗮𝗿𝗲 𝗛𝗶𝗴𝗵𝗲𝗿-𝗢𝗿𝗱𝗲𝗿 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀? - Functions that take other functions as arguments or return them - Examples: .map(), .filter(), .reduce(), .forEach() - Core concept in functional programming with JavaScript 𝟵. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝘁𝗵𝗲 𝗱𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝗰𝗲 𝗯𝗲𝘁𝘄𝗲𝗲𝗻 𝗗𝗲𝗲𝗽 𝗖𝗼𝗽𝘆 𝗮𝗻𝗱 𝗦𝗵𝗮𝗹𝗹𝗼𝘄 𝗖𝗼𝗽𝘆? - Shallow copy copies only the top level nested objects are still referenced - Object.assign() and spread {...obj} create shallow copies - Deep copy duplicates everything including nested levels 𝟭𝟬. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗼𝗽𝘁𝗶𝗼𝗻𝗮𝗹 𝗰𝗵𝗮𝗶𝗻𝗶𝗻𝗴 (?.) 𝗮𝗻𝗱 𝗻𝘂𝗹𝗹𝗶𝘀𝗵 𝗰𝗼𝗮𝗹𝗲𝘀𝗰𝗶𝗻𝗴 (??)? - ?. safely accesses nested properties without throwing if something is null/undefined - user?.address?.city returns undefined instead of crashing - ?? returns the right side only if the left is null or undefined Follow the Frontend Circle By Sakshi channel on WhatsApp: https://lnkd.in/gj5dp3fm 𝗙𝗼𝗹𝗹𝗼𝘄𝘀 𝘂𝘀 𝗵𝗲𝗿𝗲 → https://lnkd.in/geqez4re
To view or add a comment, sign in
-
🚀 JavaScript Interview Preparation Checklist (Frontend Developers) I’ve compiled this structured JavaScript topic list for interviews. Sharing it here so it can help others who are preparing for frontend roles. 📌 Core JavaScript Concepts • Scope (global, function, block) • Execution context • this keyword (different contexts) • Hoisting • Closures • Prototype chain • Type coercion • == vs === • Primitive vs non-primitive data types 📌 ES6 & Modules • let, const • Arrow functions • Template literals • Rest parameters • Spread operator • Object & array destructuring • Classes • Default parameters • Map, Set • for…of loop • import / export • Default exports 📌 Asynchronous JavaScript • Callbacks • Promises • Async/Await • Event Loop (call stack, microtask, macrotask) • Promise.all() • Promise.allSettled() • Promise.any() • Promise.race() 📌 Advanced Concepts • Function currying • Debouncing & throttling • Shallow copy vs deep copy • Call by value vs call by reference • Polyfills • Higher Order functions • IIFE 📌 DOM Manipulation & Events • getElementById • getElementsByClassName • getElementsByTagName • querySelector • querySelectorAll • addEventListener • removeEventListener • Event propagation • Event bubbling • Event capturing • Event delegation 📌 API Calls • fetch • axios • fetch vs axios 📌 Error Handling • try • catch • finally 📌 Web Storages • sessionStorage • localStorage • cookies • IndexedDb 📌 OOP in JavaScript • Constructor functions • Prototypes • __proto__ • this • call, apply, bind • ES6 classes • Inheritance • Polyfills 📌 Functions • Function expressions • Arrow functions • Named functions • Callback functions 📌 Loops • for • for…of • for…in • forEach • while • do…while 📌 Array Methods • map • filter • reduce • join • slice • splice • push • pop • shift • unshift • find 📌 String Methods • length • charAt • split • slice • substring 📌 Object Methods • Object.keys() • Object.values() • Object.entries() 📌 Browser APIs • JSON.parse() • JSON.stringify() • setTimeout() • setInterval() • clearTimeout() • clearInterval() • fetch() If you’re preparing for frontend or React interviews, covering these topics with practical examples will give you a strong JavaScript foundation 💡. #JavaScript #FrontendDevelopment #ReactJS #WebDevelopment #InterviewPreparation #SoftwareEngineering
To view or add a comment, sign in
-
-
Day 35/50 – JavaScript Interview Question? Question: What is the new keyword and what happens when you use it? Simple Answer: The new keyword creates an instance of a constructor function or class. It performs four steps: creates an empty object, sets the prototype, binds this to the new object, and returns the object (unless the constructor explicitly returns another object). 🧠 Why it matters in real projects: Understanding new is fundamental to JavaScript's prototypal inheritance and OOP patterns. It's crucial when working with classes, custom data structures, and understanding how frameworks like React create component instances. 💡 One common mistake: Forgetting new when calling a constructor, causing this to refer to the global object (or undefined in strict mode) instead of creating a new instance. Also, not knowing that arrow functions can't be used as constructors. 📌 Bonus: // Constructor function function Person(name, age) { this.name = name; this.age = age; } Person.prototype.greet = function() { return `Hello, I'm ${this.name}`; }; // Using new keyword const alice = new Person('Alice', 30); // What happens behind the scenes: function Person(name, age) { // 1. const this = Object.create(Person.prototype); // 2. this.__proto__ = Person.prototype; this.name = name; // 3. Bind properties to this this.age = age; // 4. return this; (implicit) } // Common mistakes: // ✗ Forgetting new const bob = Person('Bob', 25); // undefined, this = window! console.log(window.name); // "Bob" - polluted global! // ✓ With new const charlie = new Person('Charlie', 35); // ✓ // Arrow functions can't be constructors const PersonArrow = (name) => { this.name = name; }; const dave = new PersonArrow('Dave'); // ✗ TypeError! // ES6 Classes (syntactic sugar over prototypes) class Employee extends Person { constructor(name, age, title) { super(name, age); // Must call before using this this.title = title; } } // Custom return value overrides function Custom() { this.name = 'Test'; return { custom: true }; // This is returned instead } const obj = new Custom(); console.log(obj); // { custom: true } #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews #OOP #Constructors
To view or add a comment, sign in
-
What is result of [] === [] in javascript ? If you can’t answer this, your React apps are likely re-rendering way more than they should. In JavaScript and TypeScript, the answer is false. But why? Understanding this is the key to mastering performance and avoiding those "phantom" bugs in useEffect. 🏠 The "Two Houses" Analogy Imagine two houses. They have the exact same floor plan, the same paint color, and the same furniture. * Are they the same style? Yes. * Are they the same address? No. In JavaScript, Objects, Arrays, and Functions are Reference Types. When you create [], you aren't just creating a value; you are allocating a specific spot in memory (an address). * The first [] lives at Address A. * The second [] lives at Address B. When you use ===, JavaScript doesn't look at the "furniture" inside the array. It asks: "Are these two pointing to the exact same address?" Since Address A is not Address B, the result is false. ⚠️ Why this is a "React Killer" React uses Shallow Comparison to decide if it should re-render or trigger an effect. If you define an object or array inside your component body like this: useEffect(() => { // This runs on EVERY single render! console.log("Data fetched"); }, [ { id: 1 } ]); // ❌ New object = New reference every time Even though the ID is always 1, React sees a new address every time the component functions runs. It thinks the data has changed, so it triggers the effect again. And again. And again. ✅ How to fix it To keep your app fast, you need to preserve the Reference: * Move it outside: If the data is static, define it outside the component. * useMemo: Wrap objects/arrays in useMemo to keep the same memory address between renders. * useCallback: Use this for functions to prevent them from being "re-created" on every render. The Golden Rule: In React, it's not just about what the data is, it's about where it lives in memory. Have you ever spent hours debugging a useEffect loop only to realize it was a reference issue? Let’s talk about it in the comments! 👇 w3schools.com JavaScript Mastery #JavaScript #TypeScript #ReactJS #WebDevelopment #FrontendEngineering #CodingTips #PerformanceOptimization
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