🚀 **𝐃𝐚𝐲 5 – 𝐇𝐨𝐢𝐬𝐭𝐢𝐧𝐠 𝐢𝐧 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 (𝐂𝐥𝐞𝐚𝐫 & 𝐏𝐫𝐚𝐜𝐭𝐢𝐜𝐚𝐥 𝐄𝐱𝐩𝐥𝐚𝐧𝐚𝐭𝐢𝐨𝐧)** You might have seen this 👇 👉 Using a variable before declaring it But why does this work? 🤔 --- 💡 **What is Hoisting?** Hoisting means: 👉 Before execution, JavaScript **allocates memory for variables and functions** 👉 In simple words: **Declarations are processed before code runs** --- 💡 **Example:** ```js id="d5pro1" console.log(a); var a = 10; ``` 👉 Output: `undefined` --- 💡 **What actually happens behind the scenes?** Before execution (Memory Phase): * `a` → undefined Then execution starts: * `console.log(a)` → prints undefined * `a = 10` --- 💡 **Important Rule** 👉 JavaScript only hoists **declarations**, not values --- 💡 **var vs let vs const** 👉 **var** * Hoisted * initialized as `undefined` * can be accessed before declaration 👉 **let & const** * Hoisted * BUT not initialized --- ⚠️ **Temporal Dead Zone (TDZ)** This is the time between: 👉 variable declared 👉 and initialized During this: ❌ Accessing variable → **ReferenceError** --- 💡 **Example:** ```js id="d5pro2" console.log(a); let a = 10; ``` 👉 Output: **ReferenceError** --- ⚡ **Key Insight (Very Important)** 👉 Hoisting is NOT moving code 👉 It’s just **memory allocation before execution** --- 💡 **Why this matters?** Because it helps you understand: * unexpected `undefined` values * ReferenceErrors * how JavaScript actually runs code --- 👨💻 Continuing my JavaScript fundamentals series 👉 Next: **JavaScript Runtime & Event Loop** 👀 #JavaScript #WebDevelopment #FrontendDevelopment #Coding #SoftwareEngineer #Tech
JavaScript Hoisting Explained
More Relevant Posts
-
🚀 𝐃𝐚𝐲 6 – 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 𝐄𝐯𝐞𝐧𝐭 𝐋𝐨𝐨𝐩 (𝐒𝐢𝐦𝐩𝐥𝐞 & 𝐂𝐥𝐞𝐚𝐫) JavaScript is single-threaded… 👉 But then how does it handle things like `setTimeout`? 🤔 Let’s understand the real flow 👇 --- 💡 The Setup JavaScript uses: * Call Stack → runs code * Web APIs → handles async tasks * Callback Queue → waits for execution * Event Loop → manages everything --- 💡Example: console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); console.log("End"); --- 💡 Output: Start End Timeout --- 💡 Why? (Step-by-step) * `Start` → runs immediately * `setTimeout` → sent to Web APIs * `End` → runs immediately * Timer completes → callback goes to Queue * Event Loop checks → Stack empty * Callback pushed to Stack → executes --- ⚡ Key Insight 👉 Even with `0ms`, it does NOT run immediately 👉 It waits until the Call Stack is empty --- 💡 Simple Mental Model 👉 “Async code runs after sync code finishes” --- 💡 Why this matters? Because it explains: * execution order * async behavior * common bugs --- 👨💻 Continuing my JavaScript fundamentals series 👉 Next: **Promises (Async Made Better)** 👀 #JavaScript #WebDevelopment #FrontendDevelopment #Coding #SoftwareEngineer #Tech
To view or add a comment, sign in
-
-
Day 12/100 of JavaScript 🚀 Today’s topic: async / await "async" and "await" provide a cleaner way to work with Promises and write asynchronous code that looks like synchronous code 📍Basic example async function getData() { const res = await fetch("https://lnkd.in/gCA7VyNQ"); const data = await res.json(); console.log(data); } 📍With error handling async function getData() { try { const res = await fetch("https://lnkd.in/gCA7VyNQ"); const data = await res.json(); console.log(data); } catch (err) { console.error(err); } } 🔑 Key points : - "async" makes a function return a Promise. - "await" pauses execution until the Promise resolves. - Makes code more readable than ".then()" chaining. async/await simplifies handling asynchronous operations while still using Promises under the hood. #Day12 #JavaScript #100DaysOfCode
To view or add a comment, sign in
-
𝗧𝗵𝗲 𝗝𝗮𝗩𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗥𝘂𝗻𝘁𝗶𝗺𝗲: 𝗙𝗶𝘅𝗶𝗻𝗴 𝗬𝗼𝘂𝗿 𝗠𝗲𝗻𝘁𝗮𝗹 𝗠𝗼𝗱𝗲𝗹 You may have noticed some behaviors in JavaScript that seem strange. For example: - setTimeout doesn't interrupt loops - setTimeout doesn't block - A resolved Promise still runs after synchronous code - await pauses a function but doesn't freeze the page - Rendering sometimes waits Let's explore why this happens. JavaScript executes synchronously inside a task. Nothing can interrupt that execution. Here's what we mean by 'synchronous' and 'asynchronous': - Synchronous execution: code that runs immediately, from top to bottom via the call stack - Asynchronous code: code whose result is not available immediately, it schedules something to run later Asynchronous mechanisms do not block nor interrupt the call stack. They arrange for something to run later via scheduling. Let's test this claim with a simple for loop and setTimeout: ``` is not allowed, so we use plain text instead console.log("sync start") for (let i = 0; i < 1e9; i++) {} console.log("sync end") console.log("sync start") setTimeout(() => { console.log("timeout fired") }, 0) for (let i = 0; i <
To view or add a comment, sign in
-
Day 22/30 — JavaScript Journey ⏳ **JavaScript Async/Await** Write async code like sync — without the chaos 🚀 Still stuck in callback hell or messy `.then()` chains? Time to level up 👇 🔥 **Why Async/Await is a Game-Changer** → Reads like synchronous code → Easier debugging (try/catch) → Cleaner, more maintainable logic 💡 **Before (Promises)** ```js fetchData() .then(res => res.json()) .then(data => console.log(data)) .catch(err => console.error(err)); ``` ⚡ **After (Async/Await)** ```js async function getData() { try { const res = await fetchData(); const data = await res.json(); console.log(data); } catch (err) { console.error(err); } } ``` 🚀 **Pro Tips** ✅ Use `try/catch` for error handling ✅ Avoid blocking — use `Promise.all()` for parallel calls ✅ Don’t overuse `await` inside loops 📌 Clean code = Faster dev + Fewer bugs Save this for your next coding session 🔖 Follow for more dev insights 💡
To view or add a comment, sign in
-
-
🚨 JavaScript Gotcha: Objects as Keys?! Take a look at this 👇 const a = {}; const b = { key: 'b' }; const c = { key: 'c' }; a[b] = 123; a[c] = 456; console.log(a[b]); // ❓ 👉 What would you expect? 123 or 456? 💡 Actual Output: 456 🤯 Why does this happen? In JavaScript, object keys are always strings or symbols. So when you use an object as a key: a[b] → a["[object Object]"] a[c] → a["[object Object]"] Both b and c are converted into the same string: "[object Object]" ⚠️ That means: a[b] = 123 sets " [object Object] " → 123 a[c] = 456 overwrites it → 456 So finally: console.log(a[b]); // 456 🧠 Key Takeaways ✅ JavaScript implicitly stringifies object keys ✅ Different objects can collide into the same key ❌ Using objects as keys in plain objects is unsafe 🔥 Pro Tip If you want to use objects as keys, use a Map instead: const map = new Map(); map.set(b, 123); map.set(c, 456); console.log(map.get(b)); // 123 ✅ ✔️ Map preserves object identity ✔️ No unexpected overwrites 💬 Final Thought JavaScript often hides complexity behind simplicity. Understanding these small quirks is what separates a developer from an expert. #JavaScript #WebDevelopment #FrontendDevelopment #Programming #Coding #JavaScriptTips #JSConfusingParts #DevelopersLife #CodeNewbie #LearnToCode #SoftwareEngineering #TechTips #CodeQuality #CleanCode #100DaysOfCode #ProgrammingTips #DevCommunity #CodeChallenge #Debugging #JavaScriptDeveloper #MERNStack #FullStackDeveloper #ReactJS #NodeJS #WebDevTips #CodingLife
To view or add a comment, sign in
-
-
𝟵𝟵% 𝗼𝗳 𝗝𝗦 𝗱𝗲𝘃𝗲𝗹𝗼𝗽𝗲𝗿𝘀 𝘄𝗿𝗶𝘁𝗲 𝗮𝘀𝘆𝗻𝗰 𝗰𝗼𝗱𝗲 𝗱𝗮𝗶𝗹𝘆. 𝗕𝘂𝘁 𝗺𝗼𝘀𝘁 𝗰𝗮𝗻'𝘁 𝗲𝘅𝗽𝗹𝗮𝗶𝗻 𝘄𝗵𝘆 𝗶𝘁 𝗮𝗰𝘁𝘂𝗮𝗹𝗹𝘆 𝘄𝗼𝗿𝗸𝘀. 👇 I didn't either until I learned about the JavaScript Runtime Environment. Here's the mental model that changed everything for me: JavaScript by itself is just a language. Runtime = Engine + APIs + Event Loop 🔥 What's actually running under the hood: ⚙️ JS Engine (V8) → converts code to machine code 📞 Call Stack → runs functions one by one 🌐 Web APIs → setTimeout, DOM, fetch (NOT part of JS itself!) 📬 Callback Queue → stores async callbacks ⚡ Microtask Queue → Promises, higher priority 🔄 Event Loop → the brain connecting everything The flow: Code → Call Stack → Web APIs → Queue → Event Loop → Call Stack Right now, try this 👇 console.log("Start"); setTimeout(() => console.log("Async"), 0); console.log("End"); Output → Start, End, Async 🤯 Even with 0 ms delay, "Async" prints LAST. That's the Event Loop doing its job. 🧠 Interview tip: Q: Why can JS handle async if it's single-threaded? A: The Runtime provides Web APIs + Event Loop + Queues — not the language. If this helped, repost ♻️ to help another developer. Follow Amit Prasad for daily updates on JavaScript and DSA 🔔 💬 Comment: Did you know that setTimeout 0ms still runs last? #JavaScript #WebDevelopment #Frontend #NodeJS #100DaysOfCode #DSA #Developer #CodingLife #TechLearning
To view or add a comment, sign in
-
-
💁 Var, Let, or Const? Stop the Confusion! Choosing the right variable declaration in JavaScript is more than just a syntax choice—it's about writing predictable and bug-free code. If you are still reaching for var by habit, here is why you might want to reconsider. Let’s break down the "Big Three" across three critical dimensions: 1️⃣ Scope: Where does your variable live? - var: Function-scoped. It doesn't care about block levels like if or for loops. It leaks! - let & const: Block-scoped. They stay strictly within the curly braces {} where they are defined. This prevents accidental data leaks and collisions. 2️⃣ Hoisting: The "Magic" behavior - var: Hoisted and initialized as undefined. You can access it before the line it’s written (though it’s usually a bad idea). - let & const: Also hoisted, but they enter the Temporal Dead Zone (TDZ). Accessing them before declaration triggers a ReferenceError. 3️⃣ Reassignment & Redeclaration - var is the most "relaxed"—you can redeclare and reassign it anywhere, which often leads to accidental bugs. - let allows you to change the value (reassign) but forbids you from redeclaring the same variable in the same scope. - const is the strictest. No reassignment, no redeclaration. Once it’s set, it’s locked (though you can still mutate object properties!). 💡 My rule: Use const by default and let only when change is necessary. Forget var—modern JavaScript is all about block-scoping and reliability. Did I miss anything? How do you decide which one to use in your daily workflow? Let’s discuss below! 👇 #JavaScript #CodingTips #CleanCode #WebDev #Frontend #Programming
To view or add a comment, sign in
-
-
JavaScript is easy. Until it isn't. 😅 Every developer has been there. You're confident. Your code looks clean. You hit run. And then: " Cannot read properties of undefined (reading 'map') " The classic JavaScript wall. Here are 7 JavaScript mistakes I see developers make constantly and how to fix them: 1. Not understanding async/await ⚡ → Wrong: | const data = fetch('https://lnkd.in/dMDBzbsK'); console.log(data); // Promise {pending} | → Right: | const data = await fetch('https://lnkd.in/dMDBzbsK'); | 2. Using var instead of let/const → var is function scoped and causes weird bugs → Always use const by default. let when you need to reassign. Never var. 3. == instead of === → 0 == "0" is true in JavaScript 😱 → Always use === for comparisons. Always. 4. Mutating state directly in React → Wrong: user.name = "Shoaib" → Right: setUser({...user, name: "Shoaib"}) 5. Forgetting to handle errors in async functions → Always wrap await calls in try/catch → Silent failures are the hardest bugs to track down 6. Not cleaning up useEffect in React → Memory leaks are real → Always return a cleanup function when subscribing to events 7. Treating arrays and objects as primitives → [] === [] is false in JavaScript → Reference types don't compare like numbers — learn this early JavaScript rewards the developers who understand its quirks. 💡 Which of these caught YOU off guard when you first learned it? 👇 #JavaScript #WebDevelopment #Frontend #FullStackDeveloper #React #Programming #CodingTips #Developer #Tech #Pakistan #LearnToCode #JS #SoftwareEngineering #100DaysOfCode #PakistaniDeveloper
To view or add a comment, sign in
-
-
Day 5 ⚡ Async/Await in JavaScript — The Clean Way to Handle Async Code If you’ve struggled with .then() chains, async/await is your best friend 🚀 --- 🧠 What is async? 👉 Makes a function always return a Promise async function greet(){ return "Hello"; } greet().then(console.log); // Hello --- ⏳ What is await? 👉 Pauses execution until a Promise resolves function delay(){ return new Promise(res => setTimeout(() => res("Done"), 1000)); } async function run(){ const result = await delay(); console.log(result); } --- ⚡ Why use async/await? ✔ Cleaner than .then() chaining ✔ Looks like synchronous code ✔ Easier error handling --- ❌ Sequential vs ⚡ Parallel // ❌ Sequential (slow) const a = await fetchUser(); const b = await fetchPosts(); // ⚡ Parallel (fast) const [a, b] = await Promise.all([ fetchUser(), fetchPosts() ]); --- ⚠️ Error Handling try { const data = await fetchData(); } catch (err) { console.log("Error handled"); } --- 💡 One-line takeaway 👉 async/await = cleaner + readable way to handle Promises #JavaScript #AsyncAwait #WebDevelopment #Frontend #Coding #100DaysOfCode
To view or add a comment, sign in
-
JavaScript isn’t asynchronous… the environment is. After diving deep into asynchronous JavaScript, I realized something that completely changed how I think about writing code: We don’t “wait” for data… we design what happens when it arrives. 💡 Most developers use fetch and Promises daily, but very few truly understand what happens under the hood. Here’s the real mental model: 🔹 JavaScript is single-threaded 🔹 Heavy operations (API calls, timers) are offloaded to Web APIs 🔹 fetch() returns a Promise immediately (not the data!) 🔹 .then() doesn’t execute your function… it registers it for later 🔥 The game changer? There are actually two queues, not one: Microtask Queue (Promises) → HIGH PRIORITY Callback Queue (setTimeout, etc.) And the Event Loop always prioritizes microtasks. 💥 Example: console.log("1"); setTimeout(() => console.log("2"), 0); Promise.resolve().then(() => console.log("3")); console.log("4"); 👉 Output: 1 . 4 . 3 . 2 🧠 Why this matters: Explains unexpected execution order Makes debugging async code 10x easier Helps avoid common interview pitfalls Builds a strong foundation for React & modern frontend ⚡ Key Insight: Promises are not about cleaner syntax… They are about controlling time and execution order in a non-blocking environment. 📌 Once you truly understand: Event Loop Microtask vs Callback Queue Promise lifecycle You stop guessing… and start predicting behavior. #JavaScript #Frontend #WebDevelopment #AsyncJS #Promises #EventLoop #React #Programming
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