🚀 Day 21 – Hoisting Explained (JavaScript) Ever logged a variable before declaring it and got undefined instead of an error? 🤔 That’s hoisting in action! 💡 JavaScript moves declarations to the top of their scope before execution — but there’s a catch… 🔹 var is hoisted (but only declared) 👉 Initialized as undefined 🔹 let & const are hoisted too… BUT ❌ They live in the Temporal Dead Zone (TDZ) 👉 Accessing them early throws an error 🔹 Functions behave differently ✅ Function declarations → fully hoisted ❌ Function expressions → NOT hoisted the same way ⚠️ Why this matters? Hoisting can silently introduce bugs if you’re not careful. 🔥 Pro Tip (Angular Devs): ✔ Prefer let & const ✔ Avoid relying on hoisting ✔ Write clean, predictable code 🧠 Once you understand hoisting, debugging weird undefined issues becomes MUCH easier! 💬 Have you ever been confused by hoisting? Drop your experience below 👇 #JavaScript #Angular #Frontend #WebDevelopment #100DaysOfCode
Understanding JavaScript Hoisting in 21 Days
More Relevant Posts
-
🎡 JavaScript Event Loop — Quick Challenge Most developers get this wrong 👀 🧪 What will be the output of this code? (Check the image 👇) 👉 Drop your answer in the comments before scrolling. ⏳ Think first... . . . ✅ Answer 1. Start 4. End 3. Promise.then (Microtask) 2. setTimeout (Macrotask) 🔍 Simple Explanation JavaScript runs code in this order: 1️⃣ First → Normal (synchronous) code 2️⃣ Then → All Promises (Microtasks) 3️⃣ Finally → setTimeout (Macrotasks) 👉 Even if setTimeout is 0, it still runs later. 🧠 Takeaway Promise.then → runs sooner setTimeout → runs later Simple rule, but super useful in real projects. 💬 What was your answer? #JavaScript #EventLoop #Frontend #WebDevelopment #CodingTips
To view or add a comment, sign in
-
-
**AVOID JAVASCRIPT'S QUIET BUGS:** **Don't use ==, use ===** --- 🔺 **THE PROBLEM: == COERCION** ```js console.log([] == false); // prints true! 😅 ``` **The behind-the-scenes journey:** ``` [] ↓ (empty array) "" ↓ (string) 0 ↓ (number) false ↓ (boolean) 0 ``` Wait, why is that true? JavaScript silently converts types, leading to unexpected results. **This is confusing behavior!** --- 🔺 **THE FIX: STRICT EQUALITY** ```js console.log([] === false); // prints false! 🎉 ``` Uses strict comparison without hidden type conversions. **Predictable and safe.** --- 🔺 **NO HIDDEN CONVERSION!** --- **MAKING YOUR CODE PREDICTABLE: ALWAYS USE ===** Have you encountered confusing JavaScript type coercion? Share your experience! 👇 #javascript #webdevelopment #frontend #coding #developers #mern #learning
To view or add a comment, sign in
-
-
Day 3 ⚡ JavaScript Promises — Quick Revision If you're learning async JavaScript, understanding Promises is a must. --- 🧠 What is a Promise? 👉 A Promise represents a value that will be available now, later, or never --- 🔄 Promise States Pending ⏳ Fulfilled ✅ Rejected ❌ --- ✅ Basic Example const promise = new Promise((resolve, reject) => { resolve("Success"); }); --- 🎯 Using Promises promise .then(res => console.log(res)) .catch(err => console.log(err)); --- 🔗 Chaining (Very Important) Promise.resolve(2) .then(res => res * 2) .then(res => res + 5) .then(res => console.log(res)); // 9 👉 Each .then() must return a value --- ⚠️ Common Mistakes ❌ Not returning inside .then() ❌ Breaking the chain ❌ Delaying .then() instead of resolve() --- 💡 One-line takeaway: 👉 Promises help you control async code step-by-step --- Master this, and async JavaScript becomes much easier 🚀 #JavaScript #WebDevelopment #Frontend #Coding #100DaysOfCode
To view or add a comment, sign in
-
🚀 𝗨𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱𝗶𝗻𝗴 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗖𝗹𝗼𝘀𝘂𝗿𝗲𝘀 (The Secret Locker Story 😂) Ever felt like JavaScript remembers things even after they’re gone? 👀 Well… it actually does 😎 Let me explain 𝗖𝗹𝗼𝘀𝘂𝗿𝗲𝘀 in the simplest (and funniest) way 👇 🔐 1. Create a Locker with a Secret /* JavaScript * / function createLocker() { let secret = "💰 1 Crore Password"; return function() { console.log(secret); }; } JS be like: “Okay… I’ll keep this secret safe 🤫” 🎁 𝗧𝗮𝗸𝗲 𝘁𝗵𝗲 𝗟𝗼𝗰𝗸𝗲𝗿 𝗞𝗲𝘆 /* JavaScript * / const myLocker = createLocker(); Now the outer function is gone… finished… bye bye 👋 😳 𝗦𝗲𝗰𝗿𝗲𝘁 𝗔𝗯𝗵𝗶 𝗕𝗵𝗶 𝗟𝗶𝘃𝗲 𝗛𝗮𝗶 /* JavaScript * / myLocker(); // 💰 1 Crore Password JS says: “Function gaya toh kya hua… memory toh mere paas hai 😎” 🧠 𝗪𝗵𝗮𝘁 𝗷𝘂𝘀𝘁 𝗵𝗮𝗽𝗽𝗲𝗻𝗲𝗱? 👉 Inner function remembers outer function’s variables 👉 Even after outer function is finished 👉 This is called a Closure 😂 𝗥𝗲𝗮𝗹-𝗟𝗶𝗳𝗲 𝗔𝗻𝗮𝗹𝗼𝗴𝘆 It’s like: 👩 Mom hides sweets in a locker 🍫 🔑 Gives you the key 🏠 Leaves the house And you’re like: “अब तो मज़े ही मज़े 😎” ⚠️ 𝗜𝗺𝗽𝗼𝗿𝘁𝗮𝗻𝘁 𝗣𝗼𝗶𝗻𝘁 /* JavaScript * / const locker1 = createLocker(); const locker2 = createLocker(); 👉 Both lockers have their own secret (No sharing bro ❌😆) 💼 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗢𝗻𝗲-𝗟𝗶𝗻𝗲𝗿 Closure = A function that remembers variables from its outer scope even after the outer function has executed. 🔥 𝗡𝗼𝘄 𝘆𝗼𝘂𝗿 𝘁𝘂𝗿𝗻! Can you think of real use cases of closures? Drop in comments 👇👇 #JavaScript #WebDevelopment #Frontend #Coding #Programming #Developers #LearnToCode #Tech #SoftwareEngineering #ReactJS #100DaysOfCode #CodingLife
To view or add a comment, sign in
-
🚀 Promises vs Async/Await in JavaScript If you're working with asynchronous code in JavaScript, you’ve probably used both Promises and async/await. Here’s a simple way to understand the difference 👇 🔹 Promises -> Use .then() and .catch() for handling results. -> Chain-based approach. -> Can become harder to read with multiple steps. -> Good for handling parallel operations. Example: getUser(userId) .then(user => getOrders(user.id)) .then(orders => console.log(orders)) .catch(err => console.error(err)); 🔹 Async/Await -> Built on top of Promises (syntactic sugar) -> Cleaner, more readable (looks synchronous) -> Uses try...catch for error handling -> Easier to debug and maintain Example: async function run() { try { const user = await getUser(userId); const orders = await getOrders(user.id); console.log(orders); } catch (err) { console.error(err); } } 💡 Key Takeaway: Both do the same job, but async/await makes your code cleaner and easier to understand, especially as complexity grows. #JavaScript #WebDevelopment #AsyncProgramming #CodingTips
To view or add a comment, sign in
-
Can you explain the JavaScript event loop? Not because the concept is hard, but because explaining it clearly is what actually matters. Here’s the simplest way to break it down: JavaScript runs in a single thread, using a call stack to execute code. 1. Synchronous code runs first → Functions are pushed to the call stack and executed immediately 2. Async tasks are handled by the browser/environment → e.g. setTimeout, fetch, DOM events 3. Once the call stack is empty → the event loop starts working It processes queues in this order: 👉 Microtasks first (Promises, queueMicrotask) 👉 Then macrotasks (setTimeout, setInterval, I/O) Why? - A and D are synchronous → executed first - Promise (C) → microtask queue → runs next - setTimeout (B) → macrotask → runs last Explaining it step by step is simple — but doing it clearly makes all the difference. #Frontend #JavaScript #WebDevelopment #TechInterviews #SoftwareEngineering
To view or add a comment, sign in
-
-
"Why does JavaScript return "undefined" instead of throwing an error here?" 🤔 If you've ever faced this… you've already encountered Hoisting. Let’s understand it simply 👇 🔹 What is Hoisting? Hoisting means JavaScript moves declarations to the top of their scope before execution. But the behavior is different for "var", "let", and "const" 👇 🔹 var - Gets hoisted - Initialized with "undefined" Example: console.log(a); // 👉 undefined var a = 10; 🔹 let & const - Also hoisted - But NOT initialized This phase is called the Temporal Dead Zone (TDZ) Example: console.log(b); // ❌ ReferenceError let b = 10; 🔹 Function Hoisting Function declarations are fully hoisted ✅ Example: sayHello(); // ✅ works function sayHello() { console.log("Hello"); } 🚀 Pro Tip: Always declare variables before using them. It makes your code predictable and bug-free. 💬 Be honest — did hoisting confuse you at first? 😄 #javascript #webdevelopment #mern #coding #developers
To view or add a comment, sign in
-
Small JavaScript bugs keep escaping to production and breaking critical user flows. Debugging inconsistent runtime behavior steals time from feature delivery. ────────────────────────────── DefinitelyTyped and @types Packages: What You Need to Know Explore the importance of DefinitelyTyped and @types packages in your TypeScript projects. #typescript #definitelytyped #@types #javascript #development ────────────────────────────── Core Concept Have you ever struggled with type definitions in TypeScript? DefinitelyTyped and @types can be your best friends in making the transition smoother. Key Rules • Always check if a package has its own type definitions before looking for @types. • Use DefinitelyTyped for community-maintained types that aren't included in the package. • Keep your @types packages updated to avoid compatibility issues. 💡 Try This import { SomeType } from '@types/some-package'; const myVar: SomeType = {...}; ❓ Quick Quiz Q: What is the primary purpose of DefinitelyTyped? A: To provide high-quality type definitions for popular JavaScript libraries. 🔑 Key Takeaway Utilizing DefinitelyTyped and @types packages can dramatically improve your TypeScript experience!
To view or add a comment, sign in
-
🚨 JavaScript Gotcha: When 0 Actually Matters One of the most subtle bugs in JavaScript comes from using the logical OR (||) for default values. const timeout = userTimeout || 3000; Looks fine… until userTimeout = 0. 👉 JavaScript treats 0 as falsy, so instead of respecting your value, it silently replaces it with 3000. 💥 Result? Unexpected behavior. ✅ The Fix: Use Nullish Coalescing (??) const timeout = userTimeout ?? 3000; This only falls back when the value is null or undefined — not when it’s 0. 💡 When does 0 actually matter? ⏱️ Timeouts & delays → 0 can mean run immediately 📊 Counters & stats → 0 is a valid value, not “missing” 💰 Pricing / discounts → Free (0) ≠ undefined 🎚️ Sliders / configs → Minimum values often start at 0 🧠 Rule of thumb: Use || when you want to catch all falsy values (0, "", false, etc.) Use ?? when you only want to catch missing values (null, undefined) ⚡ Small operator. Big difference. Cleaner logic. #reactjs,#nodejs #JavaScript #WebDevelopment #CleanCode #Frontend #ProgrammingTips #DevTips #CodeQuality #SoftwareEngineering
To view or add a comment, sign in
-
-
#js #13 **Variavle Environment: Hoisting and TDZ** 1. What is Variable Environment? 👉 Variable Environment is part of the Execution Context It is where JavaScript stores variables and functions in memory before execution 📦 Think of it like: Before running code, JS does: Scan code Store variables in memory Then execute line by line 🔄 2. What is Hoisting? 👉 Hoisting means: JavaScript moves declarations to the top of their scope during memory creation phase 🔹 Example with var console.log(a); var a = 10; 👉 Internally becomes: var a; // hoisted console.log(a); // undefined a = 10; ✅ Output: undefined 🔹 Example with let / const console.log(b); let b = 20; 👉 ❌ This gives error ⚠️ Why error happens? Because of something called: 👉 TDZ (Temporal Dead Zone) 🚫 3. What is TDZ? 👉 TDZ (Temporal Dead Zone) = The time between variable declaration and initialization where it cannot be accessed 🔹 Example console.log(b); // ❌ ReferenceError let b = 20; 📊 Timeline: Start → (TDZ) → let b = 20 → usable 👉 During TDZ: Variable exists in memory But cannot be accessed 🧩 How it works internally During execution context creation: Memory phase: var a = 10; let b = 20; 👉 Stored like: a → undefined b → <uninitialized> (TDZ) Execution phase: a = 10 → updated b = 20 → initialized 🧑🍳 Simple analogy Think of variables like booking a seat 🎟 var Seat booked + you can sit anytime (even before actual time) let/const Seat booked But you can’t sit until event starts (TDZ) 🎯 Important Interview Points Hoisting happens in memory phase var is initialized with undefined let/const are in TDZ until initialized Accessing let/const before declaration → ReferenceError 🧾 Final Summary Variable Environment: Stores variables during execution context creation Hoisting: Moves declarations to top TDZ: Time where let/const cannot be accessed 💡 One-line takeaway 👉JavaScript hoists variables, but let and const stay in the TDZ until they are initialized #Javascript #ObjectOrientedProgramming #SoftwareDevelopment
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