🔥 𝐀𝐬𝐲𝐧𝐜𝐡𝐫𝐨𝐧𝐨𝐮𝐬 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 & 𝐄𝐕𝐄𝐍𝐓 𝐋𝐎𝐎𝐏 — 𝐄𝐱𝐩𝐥𝐚𝐢𝐧𝐞𝐝 𝐟𝐫𝐨𝐦 𝐒𝐜𝐫𝐚𝐭𝐜𝐡! ⚙️ 𝐓𝐡𝐞 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 𝐄𝐧𝐠𝐢𝐧𝐞 𝐚𝐧𝐝 𝐂𝐚𝐥𝐥 𝐒𝐭𝐚𝐜𝐤 • JavaScript is a synchronous, single-threaded language, meaning it has one Call Stack where all code execution happens sequentially, one line at a time. • Execution starts with the Global Execution Context being pushed onto the Call Stack. • Function invocations also create their own execution contexts which are pushed onto and then popped off the Call Stack. -------- 🌐 𝐁𝐫𝐨𝐰𝐬𝐞𝐫 𝐒𝐮𝐩𝐞𝐫𝐩𝐨𝐰𝐞𝐫𝐬 (𝐖𝐞𝐛 𝐀𝐏𝐈𝐬) • The browser (or Node.js environment) provides extra capabilities beyond the JavaScript engine, known as Web APIs. • Examples of Web APIs include: setTimeout, the DOM (Document Object Model), fetch (for network requests), and localStorage. • These APIs allow JavaScript code to perform non-blocking (asynchronous) task. ------- 🔁 𝐓𝐡𝐞 𝐄𝐯𝐞𝐧𝐭 𝐋𝐨𝐨𝐩, 𝐂𝐚𝐥𝐥𝐛𝐚𝐜𝐤 𝐐𝐮𝐞𝐮𝐞, 𝐚𝐧𝐝 𝐌𝐢𝐜𝐫𝐨𝐭𝐚𝐬𝐤 𝐐𝐮𝐞𝐮𝐞 • When an asynchronous function like 𝐬𝐞𝐭𝐓𝐢𝐦𝐞𝐨𝐮𝐭 or an 𝐞𝐯𝐞𝐧𝐭 𝐥𝐢𝐬𝐭𝐞𝐧𝐞𝐫 (𝐚𝐝𝐝𝐄𝐯𝐞𝐧𝐭𝐋𝐢𝐬𝐭𝐞𝐧𝐞𝐫) is encountered: 1. The function itself is handled by the browser's Web API environment. 2. The callback function (the code to be executed later) is registered. • Once the 𝐚𝐬𝐲𝐧𝐜𝐡𝐫𝐨𝐧𝐨𝐮𝐬 𝐭𝐚𝐬𝐤is complete (e.g., the timer expires, or a button is clicked): The registered callback function is moved to the 𝐂𝐚𝐥𝐥𝐛𝐚𝐜𝐤 𝐐𝐮𝐞𝐮𝐞 (𝐚𝐥𝐬𝐨 𝐤𝐧𝐨𝐰𝐧 𝐚𝐬 𝐭𝐡𝐞 𝐓𝐚𝐬𝐤 𝐐𝐮𝐞𝐮𝐞 𝐨𝐫 𝐌𝐚𝐜𝐫𝐨𝐭𝐚𝐬𝐤 𝐐𝐮𝐞𝐮𝐞). • The 𝐄𝐯𝐞𝐧𝐭 𝐋𝐨𝐨𝐩 is a continuously running process that checks two main things: • Is the Call Stack empty? (i.e., is all synchronous code finished executing?) • If the Call Stack is empty, are there any functions waiting in the Callback Queue or Microtask Queue? • If the Call Stack is empty, the Event Loop picks a function from the queues and pushes it onto the Call Stack for execution. --------- ⚡ 𝐌𝐢𝐜𝐫𝐨𝐭𝐚𝐬𝐤𝐬 𝐯𝐬. 𝐌𝐚𝐜𝐫𝐨𝐭𝐚𝐬𝐤𝐬 • 𝐌𝐢𝐜𝐫𝐨𝐭𝐚𝐬𝐤 𝐐𝐮𝐞𝐮𝐞 (Higher Priority): Holds callbacks from Promises (like .then() and .catch()) and Mutation Observers. •𝐂𝐚𝐥𝐥𝐛𝐚𝐜𝐤 𝐐𝐮𝐞𝐮𝐞 (Lower Priority): Holds callbacks from Web APIs like setTimeout, setInterval, and DOM event listeners. 1. 𝐌𝐢𝐜𝐫𝐨𝐭𝐚𝐬𝐤𝐬 𝐡𝐚𝐯𝐞 𝐚 𝐡𝐢𝐠𝐡𝐞𝐫 𝐩𝐫𝐢𝐨𝐫𝐢𝐭𝐲. The Event Loop will empty the entire Microtask Queue before it checks and pushes one single task from the Callback Queue onto the Call Stack. 2. If the Microtask Queue keeps adding new microtasks indefinitely, it can lead to 𝐒𝐭𝐚𝐫𝐯𝐚𝐭𝐢𝐨𝐧of the Callback Queue, preventing those tasks from ever running. -------- 🎥 Highly recommend this episode if you want to understand how JavaScript handles async code under the hood!⚡ https://lnkd.in/dpTTnJWx #JavaScript #NamasteJavaScript #EventLoop #WebDevelopment #AsyncJS #FrontendDevelopment #AkshaySaini #JavascriptMastery
How JavaScript Executes Async Code: A Deep Dive
More Relevant Posts
-
💡 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗘𝘃𝗲𝗻𝘁 𝗟𝗼𝗼𝗽 — 𝗧𝗵𝗲 𝗥𝗲𝗮𝘀𝗼𝗻 𝗬𝗼𝘂𝗿 𝗖𝗼𝗱𝗲 𝗗𝗼𝗲𝘀𝗻’𝘁 𝗥𝘂𝗻 𝗶𝗻 𝗢𝗿𝗱𝗲𝗿⚙️ Most developers know about the Event Loop, but few truly understand how JavaScript executes your code step by step — from the Global Execution Context to Web APIs, Task Queues, and Microtasks 🌀 Let’s break it down like a system engineer 👇 🧠 𝗛𝗼𝘄 𝗶𝘁 𝗦𝘁𝗮𝗿𝘁𝘀 — 𝗧𝗵𝗲 𝗚𝗹𝗼𝗯𝗮𝗹 𝗘𝘅𝗲𝗰𝘂𝘁𝗶𝗼𝗻 𝗖𝗼𝗻𝘁𝗲𝘅𝘁 When JavaScript runs, it first creates a Global Execution Context (GEC) — this contains: -> the Memory Component (variables, functions) -> the Code Component (thread of execution) It’s stored in the Call Stack, which works on a simple principle — LIFO (Last In, First Out). ⚙️ 𝗪𝗵𝗮𝘁 𝗛𝗮𝗽𝗽𝗲𝗻𝘀 𝗪𝗵𝗲𝗻 𝗬𝗼𝘂 𝗖𝗮𝗹𝗹 𝗮 𝗧𝗶𝗺𝗲𝗿 𝗼𝗿 𝗔𝗣𝗜 The browser (or Node.js) provides Web APIs like: -> setTimeout -> fetch -> DOM events These are not part of JS itself — they are handled by the environment. Once completed, their callbacks move to the Task Queues. 🧩 𝗧𝘆𝗽𝗲𝘀 𝗼𝗳 𝗧𝗮𝘀𝗸 𝗤𝘂𝗲𝘂𝗲𝘀 1️⃣ Macrotask Queue (Task Queue): Contains → setTimeout, setInterval, setImmediate, fetch callbacks, and DOM events. 2️⃣ Microtask Queue: Contains → Promise.then, async/await, and process.nextTick (Node.js). ⚡ 𝗧𝗵𝗲 𝗘𝘃𝗲𝗻𝘁 𝗟𝗼𝗼𝗽 — 𝗧𝗵𝗲 𝗕𝗿𝗮𝗶𝗻 𝗼𝗳 𝗜𝘁 𝗔𝗹𝗹 After every macrotask, the Event Loop checks the Microtask Queue — and executes all microtasks before picking up the next macrotask. Why? Because microtasks are usually short, immediate reactions (like resolved Promises) and must run before the next rendering or I/O task. 🧩 𝗤𝘂𝗶𝗰𝗸 𝗗𝗲𝗺𝗼 console.log("Start"); setTimeout(() => console.log("Macrotask"), 0); Promise.resolve().then(() => console.log("Microtask")); console.log("End"); 📤 Output: Start End Microtask Macrotask ✅ The Microtask Queue (Promise) runs before Macrotask Queue (setTimeout). 💭 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆: JavaScript is single-threaded, but not blocking — thanks to the event loop and task queues managing concurrency intelligently⚙️ Understanding this flow separates coders from engineers. #JavaScript #EventLoop #FrontendDevelopment #AsyncProgramming #WebDevelopment #FrontendEngineer #100DaysOfCode #SoftwareEngineering #TechLearning #Coding
To view or add a comment, sign in
-
-
Let’s talk about something that’s quietly changing how we write and debug JavaScript: The Power of Optional Chaining and Nullish Coalescing If you’ve ever battled nested objects in JavaScript and spent precious minutes guarding against null or undefined errors, optional chaining and nullish coalescing might just become your new best friends. Here’s the scenario: You’re working with data from APIs, user inputs, or third-party services. Sometimes, part of the data might be missing or undefined, and directly accessing deep properties can throw nasty runtime errors like “Cannot read property 'x' of undefined.” Enter optional chaining: a syntax that lets you safely access deeply nested properties without writing bulky checks. How does it look in code? Imagine you have user data that might or might not have an address object: ```javascript const user = { name: 'Jane', address: { city: 'Seattle', } }; // Traditional way const city = user && user.address && user.address.city; console.log(city); // Seattle // With optional chaining const cityOpt = user?.address?.city; console.log(cityOpt); // Seattle ``` Notice how much cleaner that is? If address is missing, cityOpt will gracefully be undefined instead of throwing an error. Now, what about default values when something is null or undefined? That’s where nullish coalescing (??) comes in. Unlike the OR operator (||), which treats many falsy values like 0 or '' as false, nullish coalescing only triggers when the value is null or undefined. Example: ```javascript const config = { timeout: 0, }; const timeout = config.timeout || 3000; // results in 3000 — not ideal if 0 is valid const timeoutFixed = config.timeout ?? 3000; // results in 0 — correct handling console.log(timeout, timeoutFixed); ``` Optional chaining + nullish coalescing together reduce boilerplate, make your code easier to read, and prevent subtle bugs. If you haven’t adopted these yet, I advise giving them a try in your next project. They’re supported in all modern browsers and Node.js versions, and once you get the hang of them, your JavaScript will feel smoother and safer. Ready to write cleaner, more robust JS? Start chaining safely today. #JavaScript #WebDevelopment #CodingTips #CleanCode #SoftwareEngineering #TechTrends #DevCommunity #Programming
To view or add a comment, sign in
-
💡 JavaScript Series | Topic 2 | Part 3 — The Event Loop, Promises & Async/Await — The Real Concurrency Engine of JavaScript👇 If you’ve ever wondered how JavaScript handles multiple tasks at once even though it’s single-threaded — the secret lies in its Event Loop. 🌀 ⚙️ 1️⃣ JavaScript’s Single Threaded Nature JavaScript runs on one thread, executing code line by line — but it uses the event loop and callback queue to handle asynchronous tasks efficiently. console.log("Start"); setTimeout(() => console.log("Async Task"), 0); console.log("End"); 🧠 Output: Start End Async Task ✅ Even with 0ms, setTimeout goes to the callback queue, not blocking the main thread. 🔁 2️⃣ The Event Loop in Action Think of it as a traffic controller: The Call Stack runs your main code (synchronous tasks). The Callback Queue stores async tasks waiting to run. The Event Loop constantly checks: 👉 “Is the stack empty?” If yes, it moves queued tasks in. That’s how JS achieves non-blocking concurrency with a single thread! 🌈 3️⃣ Promises — The Async Foundation Promises represent a value that will exist in the future. They improve callback hell with a cleaner, chainable syntax. console.log("A"); Promise.resolve().then(() => console.log("B")); console.log("C"); 🧠 Output: A C B ✅ Promises go to the microtask queue, which has higher priority than normal callbacks. ⚡ 4️⃣ Async / Await — Synchronous Power, Asynchronous Core Async/Await is just syntactic sugar over Promises — it lets you write async code that looks synchronous. async function getData() { console.log("Fetching..."); const data = await Promise.resolve("✅ Done"); console.log(data); } getData(); console.log("After getData()"); 🧠 Output: Fetching... After getData() ✅ Done ✅ The await keyword pauses the function execution until the Promise resolves — but doesn’t block the main thread! 💥 5️⃣ Event Loop Priority When both microtasks (Promises) and macrotasks (setTimeout, setInterval) exist: 👉 Microtasks always run first. setTimeout(() => console.log("Timeout"), 0); Promise.resolve().then(() => console.log("Promise")); 🧠 Output: Promise Timeout 🧠 Key Takeaways ✅ JavaScript runs single-threaded but handles async operations efficiently. ✅ The Event Loop enables concurrency via task queues. ✅ Promises and Async/Await simplify async code. ✅ Microtasks (Promises) have higher priority than Macrotasks (Timers). 💬 My Take: Understanding the Event Loop is what turns a JavaScript developer into a JavaScript engineer. 👉 Follow Rahul R Jain for real-world JavaScript and React interview questions,hands-on coding examples, and performance-driven frontend strategies that help you stand out. #JavaScript #FrontendDevelopment #WebDevelopment #AsyncProgramming #Promises #AsyncAwait #EventLoop #Coding #ReactJS #NodeJS #NextJS #WebPerformance #InterviewPrep #DeveloperCommunity #RahulRJain #TechLeadership #CareerGrowth
To view or add a comment, sign in
-
𝗨𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱𝗶𝗻𝗴 𝘁𝗵𝗲 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗘𝘃𝗲𝗻𝘁 𝗟𝗼𝗼𝗽 — 𝗠𝗮𝗰𝗿𝗼𝘁𝗮𝘀𝗸 𝘃𝘀 𝗠𝗶𝗰𝗿𝗼𝘁𝗮𝘀𝗸 𝗘𝘅𝗽𝗹𝗮𝗶𝗻𝗲𝗱 If you’ve ever wondered how JavaScript handles asynchronous code, the answer lies in one of its most powerful concepts — the Event Loop. Let’s explore how it works and why understanding it is essential for every JavaScript developer. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝘁𝗵𝗲 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗘𝘃𝗲𝗻𝘁 𝗟𝗼𝗼𝗽? JavaScript is a single-threaded language, meaning it executes one piece of code at a time. Yet modern applications constantly deal with asynchronous operations — API calls, timers, and user interactions — without freezing or blocking the UI. The secret behind this smooth execution is the Event Loop. The Event Loop coordinates between the Call Stack, Web APIs, and Task Queues, ensuring that both synchronous and asynchronous code execute efficiently and in the correct order. 𝗛𝗼𝘄 𝗜𝘁 𝗪𝗼𝗿𝗸𝘀 1. 𝗖𝗮𝗹𝗹 𝗦𝘁𝗮𝗰𝗸 – Executes synchronous code line by line. 2. 𝗪𝗲𝗯 𝗔𝗣𝗜𝘀 – Handle asynchronous tasks like setTimeout, fetch(), or DOM events. 3. 𝗧𝗮𝘀𝗸 𝗤𝘂𝗲𝘂𝗲𝘀 – Store callbacks waiting to be executed when the stack is clear. 4. 𝗘𝘃𝗲𝗻𝘁 𝗟𝗼𝗼𝗽 – Monitors the call stack and moves queued tasks into it when ready. 𝗠𝗮𝗰𝗿𝗼𝘁𝗮𝘀𝗸𝘀 𝘃𝘀 𝗠𝗶𝗰𝗿𝗼𝘁𝗮𝘀𝗸𝘀 JavaScript schedules asynchronous operations as tasks, which are divided into two categories: Macrotasks and Microtasks. 𝗠𝗮𝗰𝗿𝗼𝘁𝗮𝘀𝗸𝘀 Macrotasks include: • setTimeout() • setInterval() • setImmediate() (Node.js) • I/O callbacks • Script execution Each Macrotask executes completely before the Event Loop moves on to the next one. After each Macrotask, JavaScript checks for any pending Microtasks. 𝗠𝗶𝗰𝗿𝗼𝘁𝗮𝘀𝗸𝘀 Microtasks are smaller, high-priority tasks such as: • Promise.then() • Promise.catch() • Promise.finally() • process.nextTick() (Node.js) • queueMicrotask() Once a Macrotask finishes, all Microtasks in the queue are executed before the next Macrotask starts. This explains why Promises often resolve before setTimeout(), even if both are scheduled at the same time. 𝗘𝘅𝗮𝗺𝗽𝗹𝗲 𝗰𝗼𝗻𝘀𝗼𝗹𝗲.𝗹𝗼𝗴('𝗦𝘁𝗮𝗿𝘁'); 𝘀𝗲𝘁𝗧𝗶𝗺𝗲𝗼𝘂𝘁(() => { 𝗰𝗼𝗻𝘀𝗼𝗹𝗲.𝗹𝗼𝗴('𝗠𝗮𝗰𝗿𝗼𝘁𝗮𝘀𝗸'); }, 𝟬); 𝗣𝗿𝗼𝗺𝗶𝘀𝗲.𝗿𝗲𝘀𝗼𝗹𝘃𝗲().𝘁𝗵𝗲𝗻(() => { 𝗰𝗼𝗻𝘀𝗼𝗹𝗲.𝗹𝗼𝗴('𝗠𝗶𝗰𝗿𝗼𝘁𝗮𝘀𝗸'); }); 𝗰𝗼𝗻𝘀𝗼𝗹𝗲.𝗹𝗼𝗴('𝗘𝗻𝗱'); 𝗢𝘂𝘁𝗽𝘂𝘁: 𝗦𝘁𝗮𝗿𝘁 𝗘𝗻𝗱 𝗠𝗶𝗰𝗿𝗼𝘁𝗮𝘀𝗸 𝗠𝗮𝗰𝗿𝗼𝘁𝗮𝘀𝗸 𝗘𝘅𝗽𝗹𝗮𝗻𝗮𝘁𝗶𝗼𝗻: Start and End run first as synchronous code. The Event Loop then executes Microtasks (from the Promise). Finally, it processes the Macrotask (from setTimeout). 𝗞𝗲𝘆 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆𝘀 JavaScript is single-threaded but handles asynchronous operations efficiently through the Event Loop. Microtasks (Promises) always execute before the next Macrotask (setTimeout, etc.). Understanding this process helps developers write non-blocking, predictable, and performant code.
To view or add a comment, sign in
-
-
Day 77 of 100DaysOfCode – Understanding Async/Await, JS Engine & Geolocation API 🌍 Let’s break down three key JavaScript concepts every developer should understand 👇 🔹 1. What Is Async/Await, and How Does It Work? JavaScript is asynchronous — meaning it doesn’t wait for long tasks like fetching data or file reading to finish before moving on. That’s where async/await shines. It makes async code look simple and readable, like synchronous code. async function delayedGreeting(name) { console.log("A Messenger entered the chat..."); await new Promise(resolve => setTimeout(resolve, 2000)); console.log(`Hello, ${name}!`); } delayedGreeting("Alice"); console.log("First Printed Message!"); Here, the function pauses for 2 seconds before greeting Alice — but the rest of the program keeps running! We can also handle errors neatly using try/catch: async function fetchUserData() { try { let response = await fetch(`https://lnkd.in/dWvHabH4); let userData = await response.json(); console.log(userData); } catch (error) { console.log("Error fetching user data:", error); } } Async/await = cleaner syntax + better error handling ✨ 🔹 2. How Does the JavaScript Engine Work (and What Is a Runtime)? Think of the JavaScript engine as the “brain” that reads, understands, and executes your code. For example, Google Chrome and Node.js use the V8 Engine. When you run: const greeting = "Hello, World!"; console.log(greeting); The engine: Parses the code (checks for errors) Compiles it into machine-readable bytecode Executes it to print “Hello, World!” But the JavaScript runtime is more than just the engine — it’s the whole environment your code runs in. In the browser → runtime includes the DOM, Fetch API, and timers. In Node.js → runtime includes file systems, HTTP, etc. So the engine executes, while the runtime provides tools to interact with the outside world 🌍 🔹 3. What Is the Geolocation API and How Does getCurrentPosition Work? The Geolocation API lets websites request your location — but only with your permission (for privacy reasons). Example: navigator.geolocation.getCurrentPosition( (position) => { console.log("Latitude: " + position.coords.latitude); console.log("Longitude: " + position.coords.longitude); }, (error) => { console.log("Error: " + error.message); } ); This uses your device’s GPS, Wi-Fi, or IP address to determine your location. You get a position object that contains details like: latitude longitude accuracy altitude, and more. Always explain why your app needs location data and how it’ll be used — user trust is key. 💡 Wrap-Up: Async/Await simplifies asynchronous programming. JavaScript Engine executes code; Runtime gives it superpowers. Geolocation API helps apps know “where” the user is — responsibly.
To view or add a comment, sign in
-
🚀 𝐌𝐚𝐬𝐭𝐞𝐫𝐢𝐧𝐠 𝐂𝐚𝐥𝐥𝐛𝐚𝐜𝐤 𝐅𝐮𝐧𝐜𝐭𝐢𝐨𝐧𝐬 𝐢𝐧 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 Ever wondered how JavaScript handles tasks without blocking the main thread? That’s where 𝐂𝐚𝐥𝐥𝐛𝐚𝐜𝐤 𝐅𝐮𝐧𝐜𝐭𝐢𝐨𝐧𝐬 come into play! ⚙️ 🧩 What is a Callback Function? 𝐀 𝐜𝐚𝐥𝐥𝐛𝐚𝐜𝐤 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧 𝐢𝐬 𝐚 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧 𝐩𝐚𝐬𝐬𝐞𝐝 𝐚𝐬 𝐚𝐧 𝐚𝐫𝐠𝐮𝐦𝐞𝐧𝐭 𝐭𝐨 𝐚𝐧𝐨𝐭𝐡𝐞𝐫 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧 — 𝐚𝐧𝐝 𝐢𝐬 𝐢𝐧𝐭𝐞𝐧𝐝𝐞𝐝 𝐭𝐨 𝐛𝐞 “𝐜𝐚𝐥𝐥𝐞𝐝 𝐛𝐚𝐜𝐤” 𝐥𝐚𝐭𝐞𝐫 𝐛𝐲 𝐭𝐡𝐚𝐭 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧. 💡 Since functions in JavaScript are First-Class Citizens, they can be treated like values — passed around, returned, or assigned to variables. 📖 Think of it like this: You give function 𝐗 the responsibility to call function𝐘 later. So,𝐘becomes the callback of𝐗. ----------------------------------------------------- ⏱️ Callbacks in Action: Handling Asynchronous Operations JavaScript is 𝐬𝐢𝐧𝐠𝐥𝐞-𝐭𝐡𝐫𝐞𝐚𝐝𝐞𝐝, but callbacks allow it to perform non-blocking tasks like API calls, timers, or event handling. Here’s a simple example 👇 console.log("Start"); setTimeout(() => { console.log("⏰ This runs after 2 seconds"); }, 2000); console.log("End"); 🧠 Output: Start End ⏰ This runs after 2 seconds 💬 Explanation: When 𝐬𝐞𝐭𝐓𝐢𝐦𝐞𝐨𝐮𝐭 is called, the callback goes into the Web API environment. The JS engine keeps running other code (non-blocking). After the timer expires, the callback moves to the 𝐂𝐚𝐥𝐥𝐛𝐚𝐜𝐤 𝐐𝐮𝐞𝐮𝐞. It’s executed only when the Call Stack is empty, ensuring smooth asynchronous flow. 𝐓𝐡𝐚𝐭’𝐬 𝐭𝐡𝐞 𝐦𝐚𝐠𝐢𝐜 𝐨𝐟 𝐜𝐚𝐥𝐥𝐛𝐚𝐜𝐤𝐬 𝐞𝐧𝐚𝐛𝐥𝐢𝐧𝐠 𝐚𝐬𝐲𝐧𝐜 𝐛𝐞𝐡𝐚𝐯𝐢𝐨𝐫 𝐢𝐧 𝐚 𝐬𝐢𝐧𝐠𝐥𝐞-𝐭𝐡𝐫𝐞𝐚𝐝𝐞𝐝 𝐰𝐨𝐫𝐥𝐝! ✨ -------------------------------------------------- 🔒 𝐂𝐚𝐥𝐥𝐛𝐚𝐜𝐤𝐬 + 𝐂𝐥𝐨𝐬𝐮𝐫𝐞𝐬 = 𝐈𝐧𝐭𝐞𝐫𝐯𝐢𝐞𝐰 𝐆𝐨𝐥𝐝 💬 Here’s a classic interview problem 👇 𝐏𝐫𝐨𝐛𝐥𝐞𝐦: If you try to use a global counter variable, you risk having it modified by other parts of the code. A better solution is needed to keep the counter private and persistent. 𝐒𝐨𝐥𝐮𝐭𝐢𝐨𝐧 (𝐂𝐥𝐨𝐬𝐮𝐫𝐞): By creating a function that wraps the counter and the event listener attachment, the event handler (the callback) forms a closure over the local variable (count). 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧 𝐡𝐚𝐧𝐝𝐥𝐞𝐂𝐥𝐢𝐜𝐤() { 𝐥𝐞𝐭 𝐜𝐨𝐮𝐧𝐭 = 0; 𝐝𝐨𝐜𝐮𝐦𝐞𝐧𝐭.𝐠𝐞𝐭𝐄𝐥𝐞𝐦𝐞𝐧𝐭𝐁𝐲𝐈𝐝("𝐛𝐭𝐧").𝐚𝐝𝐝𝐄𝐯𝐞𝐧𝐭𝐋𝐢𝐬𝐭𝐞𝐧𝐞𝐫("𝐜𝐥𝐢𝐜𝐤", 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧() { 𝐜𝐨𝐮𝐧𝐭++; 𝐜𝐨𝐧𝐬𝐨𝐥𝐞.𝐥𝐨𝐠("𝐁𝐮𝐭𝐭𝐨𝐧 𝐜𝐥𝐢𝐜𝐤𝐞𝐝", 𝐜𝐨𝐮𝐧𝐭, "𝐭𝐢𝐦𝐞𝐬"); }); } 𝐡𝐚𝐧𝐝𝐥𝐞𝐂𝐥𝐢𝐜𝐤(); 🧩 Explanation: The inner callback function forms a closure over the variable count. Even after handleClick() finishes executing, count stays alive in the callback’s Lexical Environment. This keeps the counter private, persistent, and secure — no memory Leaks. #JavaScript #WebDevelopment #LearningInPublic #NamasteJavaScript #FrontendDevelopment #CodingJourney
To view or add a comment, sign in
-
Key Features of React.js v19.0 React v19.0, which has introduced several major updates focused on improving performance, simplifying common development patterns, and enhancing the developer experience. The most significant features include: New Hooks and APIs React 19 introduces new utilities to handle data fetching, form state, and UI updates more efficiently: use API: A new API that allows you to read the value of resources like Promises or Context directly within the render phase, eliminating the need for some useEffect or complex data-fetching patterns. Actions & Form Hooks: This set of features streamlines form handling: Actions: Functions (can be async) passed to form elements (e.g., <form action={actionFunction}>) that automatically manage pending states and error handling using Transitions. useActionState (formerly useFormState): A hook to manage the state and result of an Action. useFormStatus: A hook for child components to read the submission status (pending, data, etc.) of their parent <form>. useOptimistic: A hook for implementing Optimistic UI updates, where the UI instantly reflects the expected outcome of an asynchronous action while the network request is still in progress. Performance and Rendering Enhancements React Compiler (React Forget): An experimental feature aimed at automating memoization. When released, it will compile React code to plain JavaScript, automatically determining when to skip re-renders, potentially eliminating the need for manual use of memo, useMemo, and useCallback in most cases. Server Components & Actions: Features designed to improve initial page load times and simplify data fetching by rendering components and executing data mutations on the server. New directives: 'use client' (marks client-side code) and 'use server' (marks server-side functions callable from client code). Ref as a Prop: Functional components can now directly accept the ref prop, which often removes the need for the forwardRef Higher-Order Component. Asset Loading: Native support for rendering and managing <script>, <link>, and <title> tags within components, which helps React coordinate the loading of resources like stylesheets and async scripts. Developer Experience & Compatibility Improved Hydration Error Reporting: React 19 provides clearer, single error messages with a diff of the mismatched content between server-rendered and client-side HTML, making debugging easier. Support for Web Components/Custom Elements: Enhanced compatibility for integrating custom HTML elements into React applications. Context as a Provider: You can now render a Context object directly as a provider (e.g., <ThemeContext value="dark">) instead of using <ThemeContext.Provider>. React 19 makes significant moves toward simplifying asynchronous data and form handling while laying the groundwork for automatic performance optimization with the React Compiler.
To view or add a comment, sign in
-
The Object: The Organized Container of JavaScript 🗃️ In JavaScript, the Object is king. Everything that isn't a simple, raw value (like a number, text, or true/false) is treated as an Object. It's the primary way the language groups data and actions together to model real-world concepts, like a user, a car, or a settings menu. The Real-World Analogy: The Backpack 🎒 Think of a JavaScript Object as a Backpack. ⏩ It holds different items inside. ⏩ It has actions you can perform on it (like zipping it up or emptying it). The Two Parts of Every Object An Object is essentially a collection of key-value pairs, where the "key" is a label (a string) and the "value" is the actual data. These pairs are categorized into two types: 1. Properties (The Items Inside) Properties are the data or values an object holds. They describe the object. 👉 Concept: a. Property The items inside the backpack JavaScript Example: color: "red" b. Key (Name) Backpack Analogy: The label on the item's tag (e.g., brand). javaScript Example: brand c. Value Backpack Analogy: The actual item (e.g., "Nike"). javaScript Example: "Nike" 👉 How to Access: You access a property using dot notation or bracket notation. ⏩ myBackpack.brand ⏩ myBackpack["color"] 2 Methods (The Actions It Can Do) Methods are functions (actions) stored as properties within the object. They define what the object knows how to do. 👉 Concept Method Backpack Analogy:The ability to zip up the backpack or empty its contents JavaScript Example empty: function() { ... } 👉 How to Execute: You execute a method by following the object and method name with parentheses (). ✔️ myBackpack.empty() ➡️ JavaScript's Core Object Types JavaScript uses the Object structure for almost all complex data, which is why you see it everywhere: ➡️ Object Type 👉 Plain Object A single entity or configuration. Example : { name: "Shola", isAdmin: true } 👉 Array An ordered list of items. Examples: [10, 20, 30] (An Array is a special type of Object). 👉 Function A block of runnable code. Example: Functions are technically callable objects with properties. 👉 Date A specific point in time. Example: new Date() The Object and Inheritance The reason the Object is so fundamental is because of Inheritance. Every standard Object in JavaScript (unless explicitly disabled) has a secret link to an Object Prototype. ⏩ Analogy: The Backpack you bought is based on a blueprint (the Prototype). Even though you didn't define a toString() method for your backpack, it automatically inherits that method from the master Object Prototype, allowing it to display itself as a string if needed. This prototype chain is how JavaScript objects share common functionality, making the language incredibly flexible but also sometimes challenging to debug.
To view or add a comment, sign in
-
-
Day 18/100 Day 9 of JavaScript Arrow Functions in JavaScript — A Modern & Cleaner Way to Write Functions In modern JavaScript (ES6+), arrow functions provide a shorter and more elegant way to write functions. They make your code concise and improve readability, especially when working with callbacks or array methods like .map(), .filter(), and .reduce(). What is an Arrow Function? An arrow function is simply a compact syntax for defining functions using the => (arrow) symbol. Syntax: const functionName = (parameters) => { // block of code }; It’s equivalent to: function functionName(parameters) { // block of code } Example: Traditional vs Arrow Function Traditional Function: function add(a, b) { return a + b; } console.log(add(5, 3)); // Output: 8 Arrow Function: const add = (a, b) => a + b; console.log(add(5, 3)); // Output: 8 Cleaner and shorter! Key Features of Arrow Functions : No function keyword — Makes your code concise. Implicit return — If the function body has only one statement, the result is automatically returned (no need for return). Lexical this binding — Arrow functions don’t have their own this. They inherit this from the parent scope — making them great for use inside callbacks or class methods. Example: Lexical this function Person() { this.name = "Appalanaidu"; setTimeout(() => { console.log(this.name); // Works perfectly! }, 1000); } new Person(); // Output: Appalanaidu If we had used a regular function inside setTimeout, this would be undefined or refer to the global object — not the instance. Arrow functions solve that issue neatly. Quick Recap Shorter syntax Implicit return Lexical this Great for callbacks Example Use Case: Array Mapping const numbers = [1, 2, 3, 4]; const squares = numbers.map(num => num * num); console.log(squares); // Output: [1, 4, 9, 16] Arrow functions make such one-liners elegant and easy to read! Final Thought Arrow functions are not just syntactic sugar — they’re a modern JavaScript feature that simplifies code and makes your logic cleaner. Once you start using them, you’ll rarely go back to the old way! #10000coders
To view or add a comment, sign in
-
#CodingTips #BackendDevelopment #WebDevelopment #Nodejs #Expressjs #SoftwareEngineering #SoftwareDevelopment #Programming The reduce() is one of powerful #JavaScript method and also one of most confusing JavaScript method that even many developers sometimes misunderstand. the JavaScript reduce() method has many functionalities including: - It can be used for grouping objects within an array - It can be used for optimizing performance by replacing filter() method with reduce() in many circumstances - It can be used for summing an array - It can be used for flatten a list of arrays And many more. Of course I am not gonna explain it one by one. But here, I am gonna explain it to you generally, about how does reduce() method work in JavaScript? Now, let's take a look at the code snippet below. At the beginning of iterations, the accumulator (written with the sign {}) starts with the initial empty object. It's just {} (an empty object). While the currentItem is the object with the data inside like: {car_id: 1, etc}. Assume currentItem is: {car_id: 1, etc}, then when below code is executed: if (acc[currentItem.car_id]) Its like the accumulator {} will check if the currentItem.car_id, which is 1 is exist or not?. But because at the beginning is just only {} (an empty object), then it will execute the code below: acc[currentItem.car_id] = [currentItem]; It means it will generate a group of current car_id 1 with its object data, related to car id 1. So, the accumulator becoming like this: { 1: [ // coming from acc[currentItem.car_id {car_id: 1, etc} // coming from currentItem ] } And looping... Still looping until it will check again if acc[currentItem.car_id] (which is car_id is 1 for example) is exist. Because it exist, then acc[currentItem.car_id].push(currentItem); So the result will be like below: { 1: [ {car_id: 1, etc} // coming from currentItem {car_id: 1, etc} // new coming from current item ] } And it always iterate all the data until reach out the end of records. And once it's done, the final result will be like below: { 1: [ {car_id: 1, etc} {car_id: 1, etc} ], 2: [ {...}, {...}, ... ] 3: [ {...}, {...}, ... ] ... } I hope this explanation helps you to understand how JavaScript reduce() method works? Back then, I had a nightmare and difficulties to understand it, but when I know it, I started to realize how powerful it is.
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
Thanks for explaning 👍