Day 11: Callback Functions in JavaScript JavaScript is single-threaded… so how does it handle async tasks? 🤔 The answer starts with Callbacks. 🔹 What is a Callback? A callback function is a function that is: ✅ Passed as an argument to another function ✅ Executed later 🔹 Basic Example function greet(name) { console.log("Hello " + name); } function processUser(callback) { const name = "Shiv"; callback(name); } processUser(greet); Here, greet is a callback function. 🔹 Async Example setTimeout(function() { console.log("Executed after 2 seconds"); }, 2000); 👉 The function runs after a delay 👉 JavaScript does not block execution 🔥 Why Callbacks Are Important ✔️ Foundation of async JavaScript ✔️ Used in APIs, event listeners, timers ✔️ Core concept before learning Promises ⚠️ The Problem: Callback Hell When callbacks are nested too much: api1(function() { api2(function() { api3(function() { console.log("Done"); }); }); }); This leads to: ❌ Hard-to-read code ❌ Pyramid structure ❌ Difficult debugging This problem was later solved using Promises and Async/Await. #Javascript #CallBack #webdevelopment #LearnInPublic
JavaScript Callbacks: Understanding Async Tasks
More Relevant Posts
-
New Blog Published: Handling Multiple Promises in JavaScript (Promise.all(), Promise.any(), Promise.allSettled()) Ever wondered how JavaScript handles multiple asynchronous operations at the same time? In real-world applications we often run many async tasks together like fetching APIs, loading resources, or uploading files. Choosing the right Promise method can make your code much cleaner and more efficient. In this blog, I break down: Why JavaScript needs Promises for asynchronous tasks When to use Promise.all() When Promise.any() is the right choice When Promise.allSettled() becomes useful Real-life analogies and practical examples for better understanding Written in a simple way for developers who want to understand when and why to use these methods in real projects and interviews. 🔗 Read here: https://lnkd.in/gbXvwWdJ Thanks to Hitesh Choudhary sir and Piyush Garg sir, for providing this type of knowledge of web browser internal. #JavaScript #WebDevelopment #AsyncProgramming #Promises #ChaiCode
To view or add a comment, sign in
-
🚀 Understanding Global Execution Context in JavaScript Have you ever wondered what happens behind the scenes when a JavaScript program starts running? Behind the scenes, JavaScript doesn’t just run your code directly… it first creates a special environment responsible for managing memory and executing code. That is called Execution context. There are 3 types of Execution Contexts: 1) Global Execution Context: 2) Function Execution Context: 👉 Created every time a function is called. Each function gets its own separate execution context It contains: >> Local variables >>Function arguments >>Scope information 👉 Important: If you call a function 5 times → ✔️ 5 different execution contexts are created. 3) Eval Execution Context (Rare ⚠️) 👉 Created when using eval() eval("console.log('Hello')"); >> Rarely used in real projects >> Not recommended (security + performance issues. What is the Global Execution Context? The Global Execution Context is the default environment where JavaScript code begins execution. Whenever a JavaScript program runs, the engine first creates the Global Execution Context. What does the Global Execution Context contain? 1️⃣ Global Object: ->In browsers, the global object is window. 2️⃣ this keyword: ->At the global level, this refers to the global object. 3️⃣ Memory for variables and functions: ->JavaScript allocates memory for variables and functions before executing the code. JavaScript runs code in two phases 1️⃣ Memory Creation Phase: ->Variables are stored with the value undefined ->Functions are stored entirely in memory 2️⃣ Code Execution Phase: ->JavaScript executes the code line by line ->Variables receive their actual values Example: var name = "JavaScript"; function greet() { console.log("Hello")} greet(); Before execution, JavaScript stores: name → undefined greet → function Then the code runs line by line. 💬 Question: How many Execution Contexts can exist at the same time in JavaScript? #JavaScript #WebDevelopment #Programming #FrontendDevelopment
To view or add a comment, sign in
-
Blog 05 of my JS Unlocked series is live! 🚀 Arrow Functions in JavaScript: A Simpler Way to Write Functions 👇 One of the best upgrades modern JavaScript ever got — less typing, cleaner code, same result. In this one I cover: ✅ What arrow functions are and why they exist ✅ Syntax with 0, 1, and multiple parameters ✅ Implicit return — writing a function in ONE line ✅ Normal function vs arrow function — key differences ✅ Real usage inside map() on arrays ✅ Hands-on challenge to practice all of it Would love your feedback if you read it 🙏 🔗 https://lnkd.in/dYFfKgH7 Thanks to Hitesh Choudhary Sir, Piyush Garg #JavaScript #WebDevelopment #Hashnode #WebDevCohort2026 #LearningInPublic #Frontend #ES6
To view or add a comment, sign in
-
📢 Next Blog is Here! The Magic of this, call(), apply() and bind() in JavaScript ✨ 🔗 Read here: https://lnkd.in/gmmYsRqv Topics covered ✍️: ⟶ What this means in JavaScript ⟶ this inside normal functions and objects ⟶ What call() does and how to use it ⟶ What apply() does (with array arguments) ⟶ What bind() does and why it's different ⟶ Difference between call, apply, and bind ⟶ Hands-on assignment to practice all three I would also like to extend a special thanks to my mentors, Hitesh sir and Piyush sir, for their invaluable guidance and support #WebDev #JavaScript #100DaysOfCode #Chai Aur Code
To view or add a comment, sign in
-
𝗧𝗵𝗲 𝗧𝗵𝗶𝘀 𝗞𝗲𝘆𝘄𝗼𝗿𝗱 𝗧𝗿𝗮𝗽 You think you know JavaScript. But do you really understand it? Most developers do, most of the time. But sometimes JavaScript throws a puzzle that exposes a gap in your understanding. Let's look at a puzzle that has confused thousands of developers during interviews. You see this code: const user = { name: "Ebenezer", greet: function() { console.log(this.name); } }; const greetFunc = user.greet; greetFunc(); What do you think it will print? Most people say "Ebenezer". But JavaScript prints "undefined". The reason is the this keyword. When you call user.greet(), JavaScript knows the function belongs to user. So this refers to user, and this.name is "Ebenezer". But when you call greetFunc(), JavaScript asks "who owns this function?" This becomes undefined, and this.name is also undefined. Here's a simple rule to remember: this depends on how a function is called, not where it was written. You can use .bind() to make the function always remember the object. Example: const greetFunc = user.greet.bind(user); Now the output is "Ebenezer". This concept appears in event listeners and other areas of JavaScript. Many bugs happen because developers lose the correct this context. Try solving this: const person = { name: "Alex", sayHello() { console.log(this.name); } }; setTimeout(person.sayHello,
To view or add a comment, sign in
-
🚀 Understanding the JavaScript Event Loop — The Secret Behind Async JavaScript One of the most common questions in JavaScript interviews and real-world debugging is: “Why does JavaScript execute asynchronous code in a specific order?” The answer lies in the JavaScript Event Loop. JavaScript is single-threaded, meaning it can execute only one task at a time. Yet we can run asynchronous operations like API calls, timers, and promises without blocking the main thread. This is possible because of the Event Loop architecture. Let’s break it down 👇 🔹 1. Call Stack (Synchronous Execution) The Call Stack is where JavaScript executes synchronous code line by line. Every function call is pushed onto the stack and removed once executed. 🔹 2. Web APIs (Browser Features) When JavaScript encounters asynchronous operations like: setTimeout() fetch() DOM events They are handed off to Web APIs provided by the browser. 🔹 3. Task Queues There are two important queues: ✅ Microtask Queue (High Priority) Includes: Promise.then() queueMicrotask() MutationObserver These tasks execute immediately after the current call stack is empty. ✅ Macrotask Queue (Lower Priority) Includes: setTimeout() setInterval() DOM events These tasks run only after all microtasks are completed. 🔹 4. The Event Loop The Event Loop continuously checks: 1️⃣ Is the Call Stack empty? 2️⃣ Execute all Microtasks first 3️⃣ Then execute the next Macrotask It repeats this process indefinitely. 💡 Example console.log(1); setTimeout(() => console.log(2), 0); Promise.resolve().then(() => console.log(3)); console.log(4); 👉 Output: 1 4 3 2 Why? 1 and 4 run in the Call Stack Promise.then() goes to the Microtask Queue setTimeout() goes to the Macrotask Queue Microtasks run before macrotasks 📌 Execution Order: Call Stack → Microtasks → Macrotasks 🔥 Key Takeaway Understanding the Event Loop helps you: Debug asynchronous issues Write better non-blocking code Perform well in JavaScript interviews Master frameworks like React, Node.js, and Next.js #JavaScript #WebDevelopment #FrontendDevelopment #AsyncProgramming #EventLoop #Programming #Coding #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 Understanding the JavaScript Event Loop 🚀 Today I explored one of the most important concepts in JavaScript — the Event Loop. JavaScript is known as a single-threaded language, which means it can execute only one task at a time. But modern web applications perform many operations simultaneously, such as API calls, timers, and user interactions. This is where the Event Loop makes JavaScript powerful. 🔍 What’s Involved? The JavaScript runtime manages asynchronous operations using a few key components: • Call Stack – Executes synchronous code line by line • Web APIs – Handles asynchronous operations like setTimeout, DOM events, and API requests • Callback Queue – Stores callback functions waiting to be executed • Event Loop – Continuously checks if the call stack is empty and moves tasks from the queue to the stack Example: console.log("Start"); setTimeout(() => { console.log("Async Task"); }, 0); console.log("End"); Output: Start End Async Task Even though the delay is 0, the callback runs later because it first goes to the callback queue, and the event loop executes it only when the call stack becomes empty. Why It Matters: ✅ Handles Asynchronous Operations Efficiently ✅ Improves Application Performance ✅ Prevents Blocking of the Main Thread ✅ Essential for APIs, Timers, and Event Handling ✅ Core concept for Node.js and modern web applications Understanding the Event Loop helps developers write better asynchronous code and debug complex JavaScript behavior. Currently exploring deeper JavaScript concepts step by step to strengthen my development skills. 💻 #JavaScript #EventLoop #AsyncJavaScript #WebDevelopment #Developers #Programming #LearningJourney
To view or add a comment, sign in
-
8 JavaScript Concepts Every Developer Must Master JavaScript isn’t about memorizing syntax. It’s about understanding how things work under the hood. These core concepts decide whether you write code that works… or code that survives production. 1️⃣ Execution Context & Call Stack JavaScript runs inside execution contexts and manages them using the call stack. This explains: • Why functions execute in order • How stack overflows happen • Why recursion can crash your app If you don’t understand the call stack, debugging becomes guesswork. 2️⃣ Hoisting During compilation: • var is hoisted with undefined • let and const live in the Temporal Dead Zone Understanding hoisting prevents subtle bugs that look “random.” 3️⃣ Scope & Closures Closures allow functions to remember variables from their parent scope even after execution. This powers: • Data hiding • Currying • Many React hook patterns Most React bugs involving stale state? Closures. 4️⃣ The this Keyword this is NOT lexical (except in arrow functions). Its value depends on how a function is called not where it’s written. Misunderstanding this leads to unpredictable behavior. 5️⃣ Event Loop & Async JavaScript Promises, async/await, and callbacks rely on: • Call stack • Web APIs • Microtask queue • Event loop If you don’t understand the event loop, async code feels like magic. And magic breaks in production. 6️⃣ Prototypes & Inheritance JavaScript uses prototype-based inheritance — not classical inheritance. Understanding prototypes clears confusion around: • Classes • __proto__ • Method sharing 7️⃣ Shallow vs Deep Copy Objects are copied by reference. If you don’t know when to deep copy: • State mutations happen • Bugs become invisible • React re-renders behave unexpectedly 8️⃣ Debounce & Throttle Critical for performance in: • Scroll events • Resize handlers • Search inputs Without them, your app wastes CPU cycles. Final Thought If you deeply understand these concepts, frameworks become easy. If you skip them, frameworks feel simple… until production breaks. Strong JavaScript > Trendy Frameworks. #JavaScript #React #Frontend #WebDevelopment #SoftwareEngineering #MERN
To view or add a comment, sign in
-
💡 JavaScript Concept Every Developer Should Understand — this One concept that often confuses beginners in JavaScript is the this keyword. A simple way to understand it is by remembering 4 basic rules. 🚀 The 4 Rules of this in JavaScript 1️⃣ Global Context Rule If this is used outside any function, it refers to the global object. In browsers, the global object is window. console.log(this); Output: Window {. . .} So here: this → window 2️⃣ Object Method Rule When a function is called using an object, this refers to that object. const person = { name: "Rahul", greet: function() { console.log(this.name); } }; person.greet(); Execution: person.greet() So: this → person Output: Rahul 3️⃣ Normal Function Rule If a function is called normally (not through an object), this refers to the global object (window) in browsers. function show() { console.log(this); } show(); Execution: show() So: this → window 4️⃣ Arrow Function Rule Arrow functions do not create their own this. They inherit this from the surrounding scope. const obj = { value: 10, show: function() { const arrow = () => { console.log(this.value); }; arrow(); } }; obj.show(); Here: this → obj Output: 10 🧠 Simple way to remember GLOBAL SCOPE │ ├── Normal function → this = window │ OBJECT METHOD │ ├── this = object │ ARROW FUNCTION │ └── this = inherited from parent #JavaScript #WebDevelopment #CodingConcepts #FrontendDevelopment #LearnToCode
To view or add a comment, sign in
-
Revisiting the JavaScript Event Loop Sometimes going back to fundamentals is just as important as building new things. Today I revisited how the JavaScript Event Loop works a concept we use daily but don’t always think about deeply. A quick refresher: • JavaScript runs on a single-threaded call stack • Async operations are handled outside the main thread • Completed tasks move into queues • The Event Loop executes them when the call stack is empty One thing worth remembering: Promises (microtasks) are always prioritized over callbacks like setTimeout Even after working with async code regularly, understanding why things execute in a certain order is what really helps in debugging and writing better code. 📖 Article: https://lnkd.in/dnYVfHrQ #JavaScript #NodeJS #EventLoop #AsyncProgramming #BackendDevelopment
To view or add a comment, sign in
Explore related topics
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