JavaScript Hoisting: The Concept That Separates “I use JS” from “I understand JS” Hoisting is one of those JavaScript behaviors that silently explains why some code works, and why some bugs are so hard to catch. In JavaScript, code runs in two phases: 1️⃣ Compilation (creation) phase 2️⃣ Execution phase During compilation, JavaScript sets up memory for variables and functions. This is where hoisting happens. 🔹 var hoisting Only the declaration is hoisted, not the initialization. ex: console.log(x); // undefined var x = 5; Behind the scenes, JavaScript treats it like: var x; console.log(x); x = 5; No error, but also no value yet. This behavior has caused countless subtle bugs in real-world apps. 🔹 Function declarations Function declarations are fully hoisted, name and body. sayHello(); // works function sayHello() { console.log("Hello"); } This is why function declarations behave differently from function expressions. 🔹 let & const (ES6) They are hoisted, but not initialized. Accessing them before declaration throws a ReferenceError. console.log(y); // ReferenceError let y = 10; This period is known as the Temporal Dead Zone (TDZ), a design choice to make code safer and more predictable. 💡 Why this matters in real projects - Explains unexpected undefined - Helps debug scope-related issues - Shows you understand how JS actually works under the hood 📌 Best practice Don’t rely on hoisting. Write code that’s clear, intentional, and predictable, your future self (and your team) will thank you. #JavaScript #Frontend #WebDevelopment #SoftwareEngineering #CleanCode
JavaScript Hoisting: Understanding Variable and Function Behavior
More Relevant Posts
-
Understanding why Promise.all() needs an array in JavaScript Many developers try this and get confused 👇 ❌ Wrong way Promise.all(p1, p2); ✅ Correct way Promise.all([p1, p2]); 🤔 Why does this happen? Promise.all() accepts only ONE argument, and that argument must be an iterable (most commonly an array). 👉 An array allows JavaScript to loop through multiple promises and wait for all of them to resolve. ✅ Working example let p1 = new Promise((resolve) => { resolve(1); }); let p2 = new Promise((resolve) => { resolve(2); }); Promise.all([p1, p2]) .then((data) => { console.log(data); // [1, 2] }); ❌ Why `Promise.all(p1, p2)` throws an error? When you write: Promise.all(p1, p2); JavaScript treats it as: Promise.all(p1); But p1 is a "Promise object", not an iterable like an array. So JS throws: TypeError: object is not iterable 🧠 Easy way to remember > Promise.all waits for a collection of promises, not individual ones Always wrap promises inside an array. ⚠️ One more important thing If any promise rejects, Promise.all() immediately rejects. Promise.all([Promise.resolve(1), Promise.reject("Error")]) .catch(console.error); // Error 💡 Hope this helps someone avoid a common JavaScript pitfall! . . . . . #SRYTAL #JavaScript #Promises #WebDevelopment #Frontend #Learning #Promise.all #Growtogether
To view or add a comment, sign in
-
Understanding why `Promise.all()` needs an array in JavaScript Many developers try this and get confused 👇 ❌ Wrong way Promise.all(p1, p2); ✅ Correct way Promise.all([p1, p2]); 🤔 Why does this happen? Promise.all() accepts only ONE argument, and that argument must be an iterable (most commonly an array). 👉 An array allows JavaScript to loop through multiple promises and wait for all of them to resolve. ✅ Working example let p1 = new Promise((resolve) => { resolve(1); }); let p2 = new Promise((resolve) => { resolve(2); }); Promise.all([p1, p2]) .then((data) => { console.log(data); // [1, 2] }); ❌ Why `Promise.all(p1, p2)` throws an error? When you write: Promise.all(p1, p2); JavaScript treats it as: Promise.all(p1); But p1 is a "Promise object", not an iterable like an array. So JS throws: TypeError: object is not iterable 🧠 Easy way to remember > Promise.all waits for a collection of promises, not individual ones Always wrap promises inside an array. ⚠️ One more important thing If any promise rejects, Promise.all() immediately rejects. Promise.all([Promise.resolve(1), Promise.reject("Error")]) .catch(console.error); // Error 💡 Hope this helps someone avoid a common JavaScript pitfall! . . . . . #SRYTAL #JavaScript #Promises #WebDevelopment #Frontend #Learning #Promise.all #Growtogether
To view or add a comment, sign in
-
🚀 Top 20 JavaScript Concepts Every Developer Must Master. 1️⃣ Hoisting JavaScript moves variable and function declarations to the top of their scope before execution. 2️⃣ Closures A function that remembers variables from its outer scope even after the outer function has finished. 3️⃣ Scope (Global, Function, Block) Determines where variables are accessible. 4️⃣ Lexical Scope Scope is decided by where functions are written, not where they are called. 5️⃣ Prototypes & Inheritance JavaScript uses prototypal inheritance to share properties and methods between objects. 6️⃣ Event Loop Handles asynchronous operations in JavaScript’s single-threaded environment. 7️⃣ Call Stack Tracks function execution order. 8️⃣ Async/Await Cleaner way to handle asynchronous code using promises. 9️⃣ Promises Represents a value that may be available now, later, or never. 🔟 Callback Functions Functions passed as arguments to other functions. 1️⃣1️⃣ Debounce & Throttle Improve performance by controlling how often functions run. 1️⃣2️⃣ Event Delegation Attach event listeners to parent elements instead of multiple children. 1️⃣3️⃣ Truthy & Falsy Values Understanding how JavaScript evaluates values in conditions. 1️⃣4️⃣ Type Coercion JavaScript automatically converts types (== vs === difference). 1️⃣5️⃣ Destructuring Extract values from arrays or objects easily. 1️⃣6️⃣ Spread & Rest Operators Expand arrays/objects or collect function arguments. 1️⃣7️⃣ ES6 Modules Organize and reuse code using import and export. 1️⃣8️⃣ Memory Management & Garbage Collection JavaScript automatically allocates and frees memory. 1️⃣9️⃣ IIFE (Immediately Invoked Function Expression) Function that runs immediately after it’s defined. 2️⃣0️⃣ The " this" Keyword 'this'refers to the object that is calling the function. Its value depends on how the function is invoked (not where it’s defined). In arrow functions, this is inherited from the surrounding scope. #JavaScript #FrontendDeveloper #BackendDeveloper #WebDevelopment #FullstackDeveloper #Developers
To view or add a comment, sign in
-
-
Difference Between null and undefined in JavaScript A developer once told me, “My code is broken and I don’t know why.” We looked at it together, and the bug came down to one tiny detail: null vs undefined. Two words that look harmless. Two values that both seem to mean “nothing.” Yet that small misunderstanding caused hours of confusion. This happens more often than people admit. JavaScript is friendly, but it has weird behavior sometimes. And some of the biggest bugs come from the smallest concepts we rush past while learning. Understanding the difference between null and undefined is one of those quiet fundamentals that saves you from future headaches. undefined means a variable has been declared, but no value has been assigned yet. JavaScript assigns undefined by default. JavaScript let aniekan; console.log(aniekan); - undefined null on the other hand is an intentional value. It means the developer has explicitly set the variable to have no value. JavaScript let aniekan = null; Key differences undefined → value is missing or not yet assigned null → value is intentionally empty A common surprise: typeof null; - returns an"object" This is a well-known JavaScript weird behavior. Even though null is not an object, but typeof null returns "object". The difference between null and undefined is small, but it changes how you think about intention in your code. One is accidental. The other is deliberate. Knowing when to use each makes your programs easier to read and easier to trust. If this helped clarify things, give it a like so more developers can learn from it. Repost it for someone new to JavaScript. And drop your thoughts in the comments; when did null or undefined first confuse you? Let’s talk about it.
To view or add a comment, sign in
-
✅ Why JavaScript Sorted These Numbers WRONG (But Correctly 😄) This morning’s code was: const nums = [1, 10, 2, 21]; nums.sort(); console.log(nums); 💡 Correct Output [1, 10, 2, 21] Yes — not numerically sorted 👀 Let’s understand why. 🧠 Deep but Simple Explanation 🔹 How sort() works by default 👉 JavaScript converts elements to strings first 👉 Then sorts them lexicographically (dictionary order) So the numbers become strings internally: ["1", "10", "2", "21"] Now JS sorts them like words: "1" "10" "2" "21" Which gives: [1, 10, 2, 21] 🔹 Why this is dangerous Developers expect numeric sorting: [1, 2, 10, 21] But JavaScript does string comparison by default. That’s why this bug appears in: scores prices rankings pagination 🔹 Correct way to sort numbers nums.sort((a, b) => a - b); Now JavaScript compares numbers, not strings. 🎯 Key Takeaways : sort() mutates the original array Default sort() = string comparison Numbers must use a compare function This is one of the most common JS bugs 📌 If you remember only one thing: Never trust sort() without a comparator. 💬 Your Turn Did this ever break your code? 😄 Comment “Yes 😅” or “Learned today 🤯” #JavaScript #LearnJS #FrontendDevelopment #CodingInterview #ArrayMethods #TechWithVeera #WebDevelopment
To view or add a comment, sign in
-
-
🧠 Most JavaScript devs argue over this — and that’s the point 👀 (Even seniors don’t agree immediately) No frameworks. No libraries. Just how JavaScript actually schedules work. 🧩 Output-Based Question (Event Loop: microtasks vs macrotasks) console.log("A"); setTimeout(() => { console.log("B"); }, 0); Promise.resolve().then(() => { console.log("C"); }); queueMicrotask(() => { console.log("D"); }); console.log("E"); ❓ What will be printed — in the correct order? ❌ Don’t run the code 🧠 Think like the JavaScript engine A. A → E → C → D → B B. A → C → D → E → B C. A → E → D → C → B D. A → E → C → B → D 👇 Drop ONE option only (no explanations yet 😄) Why this matters Most developers know: Promises run before setTimeout But many don’t know: queueMicrotask runs before .then Console order ≠ execution intuition One wrong assumption = flaky UI or race bugs When fundamentals aren’t clear: async bugs feel random production issues are hard to reproduce debugging becomes guesswork Strong JavaScript developers don’t memorize outputs. They understand why the engine schedules work this way. 💡 I’ll pin the full breakdown after a few answers. #JavaScript #EventLoop #AsyncJavaScript #JSFundamentals #WebDevelopment #FrontendDeveloper #FullStackDeveloper #CodingInterview #DevCommunity #VibeCode
To view or add a comment, sign in
-
-
JavaScript usually feels fine until the same function suddenly behaves differently, and nothing makes sense. 👀 The code looks identical, nothing was touched, and yet the result changed. Frustration usually shows up right there. Not because of broken logic, but because 'this' isn't what it looked like. 🎭 And that's the tricky part. It's not a syntax problem; it's about execution context. In JavaScript, 'this' isn't locked in when the function is written. Its value is determined when the function runs. Change how it's called, and the behavior shifts with it. Same code, different call. Once that clicks, those "why is this undefined?" moments stop feeling random. They start feeling predictable. 🧠 The confusion fades because there's finally a mental model behind it. So here's the question worth pausing on: When exactly does JavaScript decide what 'this' points to? This is where it starts to feel obvious: https://lnkd.in/dWpngz9z
To view or add a comment, sign in
-
𝗠𝗶𝗰𝗿𝗼𝘁𝗮𝗸𝘀 𝗮𝗻𝗱 𝗠𝗮𝗰𝗿𝗼𝘁𝗮𝗸𝘀: 𝗘𝘃𝗲𝗻𝘁 𝗟𝗼𝗼𝗽 𝗗𝗲𝗺𝘆𝘀𝘁𝗶𝗳𝗶𝗲𝗱 You need to understand how JavaScript's event loop works. It helps you manage tasks and events in a non-blocking way. This is crucial for senior developers working on complex web applications. When a JavaScript program runs, it goes through a series of tasks. These tasks can be user interactions, network requests, timers, or promises. There are two types of tasks: macrotasks and microtasks. - Macrotasks include: - setTimeout - setInterval - I/O operations - Microtasks include: - Promise callbacks - Mutation Observers The event loop executes these tasks in a specific order. It runs a macrotask, then all the microtasks queued during that macrotask, until the microtask queue is empty. This means microtasks can interrupt macrotasks. Here's an example: ```javascript console.log('Start'); setTimeout(() => { console.log('Macrotask 1 completed'); }, 0); Promise.resolve().then(() => { console.log('Microtask 1 completed'); }); setTimeout(() => { console.log('Macrotask 2 completed'); }, 0); Promise.resolve().then(() => { console.log('Microtask 2 completed'); }); console.log('End'); ``` The output will be: ``` Start End Microtask 1 completed Microtask 2 completed Macrotask 1 completed Macrotask 2 completed ``` This shows that microtasks are completed before macrotasks. Understanding microtasks and macrotasks is vital for writing reliable and performant code. You can use them to ensure critical code executes immediately after the current task finishes. However, overusing microtasks can introduce performance issues. To optimize performance, ensure heavy computations or rendering logic reside within macrotasks. Use debouncing and throttling strategies for repetitive async calls. For further learning, check out: MDN Web Docs on Promises HTML Living Standard: The Event Loop JavaScript: The Definitive Guide Source: https://lnkd.in/gk_rM4Ur
To view or add a comment, sign in
-
⚔️ Normal JavaScript vs. War‑Style JavaScript What works locally often breaks in production. Here’s how to tell the difference—and why it matters. 🧪 Normal JavaScript You write it in a sandbox. The data is clean, the network is fast, and the user follows the happy path. ✅ No null or undefined to worry about ✅ Async/await with no .catch() ✅ const user = data.user.profile.email; – works every time This is lab‑grade code. Great for prototypes. Dangerous in production. 🛡️ War‑Style JavaScript This code has seen things. It’s been through code reviews, pentesting, and a 3am outage. 🔹 Defensive reading const email = data?.user?.profile?.email ?? 'fallback@example.com'; 🔹 Error handling that actually handles try { await riskyCall(); } catch (err) { logger.error(err); // Recover, don’t just crash } 🔹 Input validation – never trust the client 🔹 Performance under load – debouncing, throttling, memoization 🔹 Security – escape user input, validate JWTs, use Helmet.js 🔹 Observability – logs, metrics, structured errors War‑style code assumes the worst: 📉 Network fails 🧨 Third‑party API changes shape 🐞 Users type “eval()” into a text box 📈 The Real Difference Normal JS War‑Style JS Works on my machine Works for 10k concurrent Throws undefined Shows a friendly error One developer knows it Handover‑ready, documented “It’s fine for now” “How will this scale?” 🔥 Why This Matters War‑style isn’t over‑engineering—it’s respect. Respect for your users, your future self, and the people who will maintain your code. Start by auditing your last PR. Did you handle the unhappy paths? Did you log failures? Did you assume nothing? Normal JavaScript gets the job done. War‑style JavaScript keeps the job done. 💬 What’s one “war‑style” habit you always practice? I’ll go first: optional chaining and nullish coalescing are non‑negotiable. 👇
To view or add a comment, sign in
-
JavaScript has both 𝗳𝗼𝗿𝗘𝗮𝗰𝗵 and 𝗳𝗼𝗿...𝗼𝗳. They both loop. They both look innocent. They are not the same thing. I ignored this for way longer than I should’ve. At some point I tried to: • break out of a forEach • await inside a forEach • return values from a forEach JavaScript politely said: no ❤️ That’s when it clicked: 𝗳𝗼𝗿𝗘𝗮𝗰𝗵 is a method. 𝗳𝗼𝗿...𝗼𝗳 is an actual loop. Different tools. Different rules. Very different foot-guns. I wrote a short breakdown on: • why break and continue don’t work in forEach • why async/await + forEach is a trap • when performance actually matters (hint: almost never) • how to stop overthinking this choice altogether 👉 Read it here: https://lnkd.in/ezfQ2zhp Frontend looks simple until it isn’t. That’s what I write about. If this kind of “wait… why does JS do that?” content is your thing, I publish regularly on Substack. Subscriptions are free (and cheaper than debugging this at 2am). #frontend #uidevelopment #uiarchitecture #javascript #jsdev #ui
To view or add a comment, sign in
Explore related topics
- Clear Coding Practices for Mature Software Development
- Coding Best Practices to Reduce Developer Mistakes
- How to Write Clean, Error-Free Code
- Coding Techniques for Flexible Debugging
- Advanced Debugging Techniques for Senior Developers
- Intuitive Coding Strategies for Developers
- Principles of Elegant Code for Developers
- Strategies for Writing Robust Code in 2025
- Improving Code Clarity for Senior Developers
- How to Add Code Cleanup to Development Workflow
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
Which is why I believe the using let and const is better since you know the scope of the variables.