What is Hoisting in JavaScript? Hoisting is JavaScript's default behavior of moving variable and function declarations to the top of their scope before execution. This means you can sometimes use variables or functions before they are declared in the code. 1️⃣ Variable Hoisting with var console.log(a); // undefined var a = 10; Behind the scenes, JavaScript interprets it like this: var a; console.log(a); // undefined a = 10; 👉 The declaration is hoisted, but not the assignment. 2️⃣ Hoisting with let and const console.log(a); // ❌ ReferenceError let a = 10; Variables declared with let and const are hoisted but placed in the Temporal Dead Zone (TDZ), meaning they cannot be accessed before initialization. 3️⃣ Function Hoisting Function declarations are fully hoisted. greet(); function greet() { console.log("Hello JavaScript"); } This works because the entire function definition is hoisted. #javascript #webdevelopment #frontenddeveloper #mernstack #codinginterview #softwareengineering
JavaScript Hoisting Explained: var, let, and Function Declarations
More Relevant Posts
-
🧠 Day 4 of 21 days challenge JavaScript Hoisting 🤯 // var → undefined // let/const → error Why different behavior? Hoisting is a JavaScript behavior where variable and function declarations are moved to the top of their scope before execution. Only declarations are hoisted, not initializations. For easy understanding :- Hoisting = moving declarations to top var is hoisted with undefined let & const are hoisted but not initialized 👉 That’s why var gives undefined but let/const give error For example :- Normal code : console.log(score); // undefined var score = 90; JS will do this internally: var score; // first reserve console.log(score); // undefined score = 90; // then assign value This changed how I understand variable behavior 🚀 #JavaScript #Hoisting #Frontend
To view or add a comment, sign in
-
-
🚀 JavaScript Variables (var, let, const) & Hoisting. Before JavaScript executes your code… Have you ever wondered where variables are stored? 🤔 🧠 What is a Variable? A variable is a named container used to store data. ⚙️ JavaScript gives us 3 ways to declare variables: var a = 10; let b = 20; const c = 30; 🧠 What is Hoisting? 👉 Hoisting is JavaScript’s behavior of moving declarations to the top of their scope before execution. 👉 In simple words: You can access variables and functions even before they are initialized. 📦 Example with var: console.log(x); // undefined var x = 5; 🚫 Example with let: console.log(y); // ❌ ReferenceError let y = 10; 🔒 Same with const: console.log(z); // ❌ ReferenceError const z = 15; 🎯 Key Differences: • var → hoisted + initialized (undefined) • let & const → hoisted but NOT initialized (Temporal Dead Zone) 👉 “In the next post, we’ll dive into Scope — the concept that truly defines how variables behave in JavaScript.” #JavaScript #WebDevelopment #Frontend #Coding
To view or add a comment, sign in
-
⚡ Understanding the JavaScript Event Loop (Simplified) One concept that helped me understand JavaScript much better is the Event Loop. JavaScript is single-threaded, but it can still handle asynchronous operations like API calls, timers, and promises. How? Because of the Event Loop. In simple terms: 1️⃣ JavaScript executes synchronous code first (Call Stack). 2️⃣ Async tasks like setTimeout or API requests go to Web APIs. 3️⃣ Once completed, they move to the Callback Queue. 4️⃣ The Event Loop checks if the call stack is empty and pushes callbacks back for execution. This is why code like this works: console.log("Start"); setTimeout(() => { console.log("Async Task"); }, 0); console.log("End"); Output: Start End Async Task Even with 0 delay, async tasks wait until the call stack is empty. 💬 When did you first learn about the Event Loop? #JavaScript #WebDevelopment #FrontendDevelopment #AsyncProgramming
To view or add a comment, sign in
-
⚡ A Common JavaScript Misconception About the Event Loop Many developers think: "setTimeout(fn, 0) runs immediately." That’s incorrect. Even with 0 milliseconds, the callback still goes through the Event Loop cycle. Example: console.log("A"); setTimeout(() => console.log("B"), 0); Promise.resolve().then(() => console.log("C")); console.log("D"); Output: A D C B Why? Because JavaScript has two queues: 🔹 Microtask Queue → Promises, MutationObserver 🔹 Callback Queue → setTimeout, setInterval The Event Loop always processes microtasks first. Understanding this difference is critical when debugging async behavior in real applications. Master the Event Loop → Master asynchronous JavaScript. #javascript #asyncjavascript #webdevelopment #frontend #mernstack
To view or add a comment, sign in
-
-
💡 JavaScript Practice — Counting Vowels A small problem, but a good test of logic: 👉 Count the number of vowels in a string Here’s my solution: const str = "javascript"; const vowels = "aeiouAEIOU"; let count = 0; for (let letter of str) { for (let vowel of vowels) { if (letter === vowel) count++; } } console.log(count); 🧠 What this taught me: • How nested loops actually work in real scenarios • Breaking a problem into smaller steps • Writing simple, readable logic ⚡ Next step: I’ll try optimizing this (maybe using includes() or a better approach) If you have a cleaner or more efficient solution, I’d love to see it. #JavaScript #ProblemSolving #WebDevelopment #LearningInPublic
To view or add a comment, sign in
-
⚠️ JavaScript Function Expression — A Common Corner Case That Trips Developers 🔍 The Corner Case: Hoisting Behavior console.log(add(2, 3)); // ❌ TypeError: add is not a function var add = function(a, b) { return a + b; }; 👉 Why does this fail? Because only the variable declaration (var add) is hoisted, not the function itself. So internally, JavaScript sees this as: var add; console.log(add(2, 3)); // ❌ add is undefined add = function(a, b) { return a + b; }; ✅ Now Compare with Function Declaration console.log(add(2, 3)); // ✅ 5 function add(a, b) { return a + b; } 👉 Entire function is hoisted — so it works! 💥 Another Tricky Case (Named Function Expression) const foo = function bar() { console.log(typeof bar); }; foo(); // ✅ function bar(); // ❌ ReferenceError: bar is not defined 👉 bar is only accessible inside the function, not outside! 🎯 Key Takeaways ✔ Function expressions are NOT fully hoisted ✔ Only variable declarations are hoisted (var, let, const behave differently) ✔ Named function expressions have limited scope ✔ Always define function expressions before using them #JavaScript #Frontend #CodingInterview #WebDevelopment #JSConcepts #100DaysOfCode
To view or add a comment, sign in
-
🧠 Day 3 of 21 days challenge JavaScript Event Loop 🤯 Event Loop is a mechanism in JavaScript that handles execution of asynchronous code. It continuously checks the call stack and callback queue. If the stack is empty, it moves tasks from the queue to the stack for execution. For example :- console.log("Start"); console.log("End"); console.log("Timeout"); Wait… why this order? Because JavaScript doesn’t run everything instantly. It uses: • Call Stack • Web APIs • Callback Queue Event Loop decides what runs next. 💤For easy understanding :- Event Loop = decides execution order Sync code runs first Async code waits in queue Then runs after the stack is empty 👉 That’s why “Timeout” runs last This changed how I understand async code 🚀 #JavaScript #EventLoop #Async
To view or add a comment, sign in
-
-
Just built a simple yet functional Stopwatch using HTML, CSS, and JavaScript ( This project helped me strengthen my understanding of: • DOM manipulation • Event handling (Start, Stop, Reset) • Time logic and intervals in JavaScript • Structuring clean and responsive Ul with CSS Watching the timer run in real-time after writing the logic from scratch was a satisfying moment. Small projects like this continue to sharpen my problem-solving skills and build my confidence as a developer. Next step: improving the design and adding more advanced features #WebDevelopment #JavaScript #HTML #CSS #FrontendDevelopment #SoftwareEngineering
To view or add a comment, sign in
-
Just built a simple modal popup using HTML, CSS, and JavaScript. Features: • Open and close buttons • Close on Escape key • Click outside to close • Clean UI with background image This helped me understand DOM manipulation, event handling, and class toggling in JavaScript. Still learning and improving step by step. #HTML #CSS #JavaScript #WebDevelopment #LearningByDoing
To view or add a comment, sign in
-
If JavaScript is single‑threaded, how does it still handle Promises, API calls, and Timers without blocking the application? The answer lies in the Event Loop. Let’s take a simple example: What would be the output of the below code? console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); Some may guess the output to be: Start End Timeout Promise But the actual output is: Start End Promise Timeout So what is happening behind the scenes? 🔵 Synchronous Code Being synchronous, console.log("Start") and console.log("End") run immediately in the Call Stack. 🔵 Promises Resolved promises go to the Microtask Queue which is executed next. 🔵 setTimeout Timer callbacks go to the Macrotask Queue, even if the delay is '0ms', which is executed last. ✅ Simple flow to remember Synchronous Code → Promises (Microtasks) → setTimeout (Macrotasks) So even with 0 delay, Promises will always execute before setTimeout. Understanding this small but important detail will help developers debug async behavior and write more predictable JavaScript applications. #javascript #webdevelopment #eventloop #asyncprogramming
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