Why does foo() sometimes log "B" and other times "A"? Understanding JavaScript Hoisting with var and Function Declarations 🚀 If you've ever encountered this code snippet and wondered why the first call logs "B" and the later call logs "A", you’re not alone: What’s going on here? At first glance, one might expect foo to be undefined before the variable assignment line, because of var foo, causing foo() to throw an error on the first call. But JavaScript behaves a bit differently. Here’s why: Key points about hoisting: 1️⃣ Function declarations are fully hoisted — their binding and body are available before execution starts. 2️⃣ Variable declarations (var) are hoisted too but only their names — NOT their assignments. 3️⃣ If a function declaration and a variable declaration share the same name, the function declaration takes priority during hoisting. How execution unfolds step-by-step: The function foo that logs "B" is hoisted — so at runtime, before any code executes, foo points to this function. The variable declaration var foo; is also hoisted, but does not overwrite the function at this stage. When foo(); executes the first time, it calls the hoisted function and logs "B". Then the assignment foo = function() { console.log("A") } runs, overwriting the original function. The second foo(); call then logs "A". Why doesn’t var foo reset foo to undefined before assignment? Because hoisting only lifts the declaration name, not the initialization. The function declaration’s initialization happens before variable declarations. Only when the interpreter reaches the line with the assignment, does foo get assigned the new function expression — and that replaces the original function. Function declarations hoist their definitions first — foo exists as a function at the start. var declarations hoist the variable name but do not initialize it until runtime. The assignment to foo happens in order and overwrites the hoisted function later. Understanding these nuances helps avoid confusions and tricky bugs! Remember: hoisting is about declarations only, not assignments. If this cleared up a mystery for you, or if you have other JavaScript hoisting quirks you want to discuss, drop a comment below! 👇✨ #JavaScript #WebDevelopment #CodingTips #Programming #JavaScriptTips #Hoisting #CodeUnderstanding
JavaScript Hoisting: Function Declarations vs Var Declarations
More Relevant Posts
-
🚨 A small JavaScript behavior wasted 30 minutes of my debugging time today. I was extracting payment_ids from an array and wrote this: let paymentIds = filterArray ?.map(item => item.payment_id) .filter(item => item != null) .join(","); if (paymentIds.length > 0) { // run logic } And the condition paymentIds.length > 0 was always true. At first, I thought this was a bug in my code. But it turns out that JavaScript works this way. filterArray = [{id:1},{id:2},{id:3}] If the objects don’t contain payment_id, this happens: [undefined, undefined, undefined] and paymentIds outputs ",,,," So the string still has a length greater than 0, even though there are no real values. So, the correct approach is let paymentIds=filterArray ?.map(i => i.payment_id) .filter(Boolean) .join(","); Lesson learned When working with arrays in JavaScript: 👉 map() doesn't remove invalid values. 👉 join() will still create separators for undefined items. 👉 Checking string length alone can be misleading. Sometimes the smallest behaviors cause the biggest debugging sessions. #javascript #webdevelopment #frontend #reactjs #softwareengineering #codingtips
To view or add a comment, sign in
-
Just published a new blog on 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗖𝗼𝗻𝘁𝗿𝗼𝗹 𝗙𝗹𝗼𝘄. 🚀 Covered how programs make decisions using if, else, and switch, explained with simple examples. 𝗥𝗲𝗮𝗱 𝗵𝗲𝗿𝗲: https://lnkd.in/gGKjx_vS Chai Aur Code ☕ #JavaScript
To view or add a comment, sign in
-
🚀 Understanding Hoisting in JavaScript Many developers hear that JavaScript moves variables and functions to the top, but what actually happens behind the scenes? In JavaScript, hoisting occurs during the compilation phase, before the code executes. The JavaScript engine first scans the entire code and allocates memory for variables and functions. This means: • var variables are hoisted and initialized with undefined • let and const are also hoisted but remain in the Temporal Dead Zone (TDZ) until their declaration line is reached • Function declarations are fully hoisted, allowing them to be called before they appear in the code Example: console.log(a); var a = 10; Output: undefined Internally JavaScript treats it like this: var a; console.log(a); a = 10; ⚠️ Important: JavaScript does not physically move code to the top. During compilation the engine simply registers declarations in memory before execution begins. Understanding hoisting helps developers better grasp execution context, scope, and the JavaScript engine's behavior. #JavaScript #WebDevelopment #Frontend #Programming #Coding
To view or add a comment, sign in
-
💻 JavaScript Intermediate – Custom map() Function The map() method is widely used to transform arrays. Here’s how you can implement it manually. 📌 Problem: Apply a function to each element of an array and return a new array. function customMap(arr, callback) { let result = []; for (let i = 0; i < arr.length; i++) { result.push(callback(arr[i])); } return result; } let numbers = [1, 2, 3]; let doubled = customMap(numbers, function(num) { return num * 2; }); console.log(doubled); 📤 Output: [2, 4, 6] 📖 Explanation: • map() creates a new array by applying a function to each element. • Here, we manually implemented the same logic using a loop and callback. 💡 Tip: Understanding this helps you grasp how higher-order functions work in JavaScript. #JavaScript #Coding #WebDevelopment #FrontendDevelopment #LearnToCode #ProgrammingTips
To view or add a comment, sign in
-
-
JavaScript Hoisting Explained Part 3.......................... In JavaScript, hoisting behaves differently depending on how a function is defined. Function Declarations are fully hoisted — the entire function body is moved to the top of its scope during compilation. This means you can call the function before it's defined in the code without any errors. Function Expressions are only partially hoisted — when assigned to a var, only the variable name is hoisted, initialized as undefined. The function assignment stays in place, so calling it before the definition throws a TypeError. Key Takeaway: ✅ function sayHello() {} → callable before declaration ❌ var sayHi = function() {} → calling before assignment causes an error. Always prefer function declarations when you need early availability, or use const/let with function expressions to avoid hoisting confusion altogether. #JavaScript #WebDev #Frontend #JS #Hoisting #FunctionDeclaration #FunctionExpression #CodingTips #Programming #100DaysOfCode #LearnToCode #JSFundamentals #SoftwareDevelopment #Dev
To view or add a comment, sign in
-
-
🧠 JavaScript Concept: Hoisting Explained Hoisting is JavaScript's behavior of moving variable and function declarations to the top of their scope before execution. This is why we can sometimes use variables or functions before they are declared. Example: console.log(name); // undefined var name = "Arun"; Why undefined? Because JavaScript internally treats it like this: var name; console.log(name); name = "Arun"; 🔹 Important Points: • "var" is hoisted and initialized with "undefined" • Function declarations are fully hoisted • "let" and "const" are hoisted but stay in the Temporal Dead Zone (TDZ) ⚠️ Accessing "let" or "const" before declaration will throw an error. 📌 Best Practice: Avoid relying on hoisting — always declare variables at the top for better readability. #javascript #frontenddevelopment #reactjs #webdevelopment #coding
To view or add a comment, sign in
-
-
🚨 Confused about Hoisting in JavaScript? You’re not alone. 💡 It’s one of those concepts that feels strange at first — but once you get it, your understanding of JavaScript becomes much stronger. 🔹 Hoisting • JavaScript moves declarations to the top of their scope • Happens during the compilation phase • Allows variables and functions to be used before declaration 🔹 var vs let vs const • var → hoisted and initialized with undefined • let & const → hoisted but NOT initialized (Temporal Dead Zone) • Accessing them before declaration throws an error 🔹 Functions • Function declarations → fully hoisted • Function expressions → behave like variables (not fully hoisted) ⚡ Quick rule many developers follow: • var → hoisted safely (but can cause bugs) • let/const → safer, but respect TDZ • Functions → declarations hoisted, expressions not 📌 Hoisting doesn’t move your code — JavaScript just changes how it reads it internally. #JavaScript #WebDevelopment #FrontendDevelopment #Coding #LearnToCode #100DaysOfCode
To view or add a comment, sign in
-
-
Function declarations and function expressions look almost identical, but JavaScript treats them differently under the hood, especially because of hoisting. So I wrote a short blog explaining: • What functions are and why we use them • Function declaration syntax • Function expression syntax • Key differences between the two • A simple explanation of hoisting • When to use each approach If you are starting with JavaScript, this distinction will save you from some confusing bugs later 👇 https://lnkd.in/gpYx4vyy Thanks to Nikhil Rathore Hitesh Choudhary Chai Aur Code Piyush Garg Akash Kadlag Jay Kadlag for guidance! #JavaScript #WebDevelopment #LearnInPublic #100DaysOfCode #FrontendDevelopment #Programming #CodingJourney #Developers #TechBlog
To view or add a comment, sign in
-
💡 Understanding the JavaScript Event Loop (Made Simple) When I started learning JavaScript, I was confused about how setTimeout, button clicks, and API calls worked — especially since JavaScript is single-threaded. This visual really helped me understand what happens behind the scenes: 👉 1. Call Stack – Runs code line by line (synchronous code) 👉 2. Web APIs – Handles async tasks like timers and fetch requests 👉 3. Callback Queue – Stores completed async callbacks 👉 4. Event Loop – Moves callbacks to the stack when it’s empty 🔎 Simple Example: console.log("Start"); setTimeout(() => { console.log("Inside Timeout"); }, 0); console.log("End"); 👉 What do you think the output will be? The output is: Start End Inside Timeout Even though the timeout is set to 0 milliseconds, it doesn’t run immediately. Here’s why: 1️⃣ "Start" goes to the call stack → executes 2️⃣ setTimeout moves to Web APIs 3️⃣ "End" executes 4️⃣ The callback moves to the queue 5️⃣ The Event Loop waits until the stack is empty 6️⃣ Then it pushes "Inside Timeout" to the stack That’s the Event Loop in action 🚀 Understanding this concept made: ✅ Promises easier ✅ Async/Await clearer ✅ Debugging smoother If you're learning JavaScript, mastering the Event Loop is a big step forward. #JavaScript #WebDevelopment #BeginnerDeveloper #AsyncProgramming #FrontendDevelopment #mernstack #fullstack
To view or add a comment, sign in
-
-
Function Declarations and Function Expressions may look similar but they behave very differently because of hoisting. In my latest article, I break down • Declaration vs Expression syntax • How hoisting works in simple terms • Why one can be called before definition • When to use each in real projects Understanding this difference changes how you structure your code. Read here : https://lnkd.in/g9tyAdgM Grateful to be learning through the Chai Aur Code community and mentors Hitesh Choudhary and Piyush Garg. #javascript
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
💯 Great breakdown!JS hoisting trips up even experienced devs — and this example perfectly shows how function declarations and var behave very differently 🧠⚡ 🟦 Function declarations → fully hoisted🟧 var → name only hoisted➡️ Function wins first, assignment overrides later Super clear explanation — love how you walked through it step‑by‑step! 🙌✨