let is hoisted. But not the way most people think. Here's what actually happens under the hood. The Question A junior asked me: "If let isn't hoisted, why do I get 'Cannot access before initialization' instead of 'not defined'?" Fair question. The error message itself is a clue. I knew let was hoisted. But I didn't actually know how it worked under the hood until I dug into the spec. What Actually Happens JavaScript runs in two phases: Creation phase: Scans your code. Registers all identifiers in their respective lexical environments. This is hoisting. Execution phase: Runs code line by line. Both var and let get hoisted. Both get registered in scope. The difference is initialization. The Key Difference var gets initialized to undefined immediately during hoisting. You can access it anywhere, you just get undefined if you use it before assignment. let gets registered but stays uninitialized. The engine knows it exists, but won't let you touch it until the declaration line. Try to access it? ReferenceError. This is the Temporal Dead Zone. Why It Matters With var, you can accidentally use a variable before it's declared. You get undefined. The bug might not show up until later, somewhere else in your code. With let, you crash immediately at the exact line where you made the mistake. Clear error. Easy fix. The Proof Try declaring let x inside a function where an outer x exists. Access it before the declaration. You'll get an error about the inner x, proving it was already hoisted and is shadowing the outer one. It's just stuck in the TDZ. If let wasn't hoisted, you'd access the outer variable instead. Bottom Line let is hoisted. Its binding exists from the start of the scope. It's just locked until initialization. One small design choice that catches bugs early instead of letting them hide. How many of you thought let wasn't hoisted at all? #JavaScript #WebDevelopment #Programming #NodeJS #SoftwareEngineering
JavaScript Hoisting: Let vs Var Explained
More Relevant Posts
-
JavaScript Variables & Scope — A Concept Every Developer Must Master A lot of JavaScript bugs don’t come from complex logic. They come from misunderstanding scope. Let’s break it down in a simple way. 1️⃣ var • Function-scoped • Hoisted and initialized as undefined • Can easily lead to unexpected bugs 2️⃣ let • Block-scoped • Not accessible before declaration • Safer and more predictable 3️⃣ const • Block-scoped • Cannot be reassigned • Best choice in most cases Key takeaway: 👉 Use const by default 👉 Use let when reassignment is required 👉 Avoid var in modern JavaScript When you truly understand scope, you get: • Fewer bugs • Cleaner, more readable code • Better performance • Stronger answers in interviews If you’re serious about JavaScript, this is non-negotiable knowledge. What confused you the most when you first learned var, let, and const? #JavaScript #WebDevelopment #FrontendDeveloper #MERN #CleanCode #Programming #SoftwareEngineering
To view or add a comment, sign in
-
-
JavaScript doesn't read your code from top to bottom. 🧠 Ever wondered why you can call a function before you’ve even defined it? Or why a variable returns undefined instead of crashing your app? Welcome to Hoisting—the JavaScript engine’s way of "scanning" your code before it actually runs. Understanding this is the difference between guessing why your code works and actually knowing. 🏗️ What is Hoisting, really? Before executing a single line of code, the JS engine sets aside memory for your variables and functions. It "lifts" the declarations to the top of their scope. But here’s the catch: It only lifts the name, not the value. 🔴 var | The "Silent Bug" Creator var is hoisted and initialized as undefined. The Result: You can access the variable before its line, but you’ll get undefined. No error, just a silent logical failure. 🟡 let & const | The "Dead Zone" Contrary to popular belief, let and const are hoisted. However, they aren't initialized. The TDZ: They live in the "Temporal Dead Zone" from the start of the block until the line they are declared. The Result: Accessing them early triggers a ReferenceError. This is a good thing—it forces cleaner code. 🟢 Functions | The "VIPs" Function declarations are fully hoisted. You can call them at the very top of your file, even if they are written at the bottom. Warning: This does not apply to Arrow Functions or Function Expressions (they follow variable rules!). 🧠 The Dev Mental Model Think of it as two separate passes: Pass 1 (Setup): JS finds all the names (Declarations) and allocates memory. Pass 2 (Execution): JS runs the logic and assigns the values. 🔑 The Golden Rule To avoid hoisting headaches: Always use const or let. Always declare your variables at the top of their scope. Don't rely on hoisting for functions; it makes code harder to read. Did Hoisting ever save your code or did it cause a week-long debugging nightmare? Let's hear your horror stories below! #JavaScript #WebDevelopment #SoftwareEngineering #CodingInterviews #Programming #CleanCode
To view or add a comment, sign in
-
-
Asynchronous JavaScript is a game-changer. It's all about performing tasks without freezing your program. You can fetch data from a server, read files, or handle user events - and the entire program won't come to a grinding halt. So, how does it work? Well, JavaScript uses the event loop, call stack, and task queues to make this magic happen. And over time, various language constructs have evolved to make asynchronous programming easier - it's like the language has been learning and adapting, you know? Here's the thing: asynchronous programming became necessary because we needed to fetch data from servers without reloading the page, handle user input while background tasks run, and avoid blocking the UI thread. It's all about creating a seamless user experience. Asynchronous JavaScript has been around for over 20 years - and it's come a long way. Let's take a quick look at some key milestones: - The early days (1995-2004) were all about basic event handlers and setTimeout. - Then, in 2005-2006, AJAX and XMLHttpRequest callbacks came onto the scene. - Node.js popularized callbacks in - but, let's be real, callback hell was a real thing. - Luckily, Promises emerged, and things started to look up. - In 2015, Native Promises and Generators were introduced - and that's when things started to get really interesting. - Async/await was introduced, and it was like a breath of fresh air. - And, more recently, top-level await and async iterators were added to the mix. Now, you can use async/await to write readable, sequential code - it's built on Promises, and it provides a way better developer experience. So, if you want to learn more, check out this article: https://lnkd.in/gCNqkmVA Or, join the conversation here: https://lnkd.in/ghgjYknN #AsynchronousJavaScript #JavaScript #AsyncAwait #Innovation #Programming #Development #Code #SoftwareEngineering #WebDevelopment #CodingCommunity
To view or add a comment, sign in
-
🚀 JavaScript Challenge: Do you know how Closures and Event Loops work? Pop quiz for my fellow developers! 💻 Look at the code snippet below. What do you think the console will output? Is it 0, 1, 2? Or perhaps 3, 3, 3? 💡 The Explanation If you guessed 3, 3, 3, you’re right! But do you know why? This is a classic interview question that tests your understanding of Scope, Closures, and the Event Loop. Here is the breakdown: 1. Global Scope: The variable i is declared using let outside the loop. This means there is only one instance of i shared across every iteration. 2. The Event Loop: setTimeout is asynchronous. It schedules the log function to run after 100ms. By the time that 100ms passes, the for loop has already finished executing. 3. The Final Value: When the loop finishes, the value of i has been incremented to 3 (the condition that broke the loop). 4. Closure in Action: When the three scheduled log functions finally execute, they all look at that same single variable i, which is now 3 🛠️ How to fix it? If you wanted to output 0, 1, 2, the simplest fix is to move the declaration of i inside the loop head: for (let i = 0; i < 3; i++). This creates a block scope for each iteration, effectively "capturing" the value of i at that specific moment. Why this matters: Writing clean code is about more than just making it work—it's about understanding the underlying mechanics of the language to prevent memory leaks and unexpected bugs. #JavaScript #WebDevelopment #CodingChallenge #SoftwareEngineering #Frontend #TechCommunity
To view or add a comment, sign in
-
-
JavaScript is one of the most powerful and versatile languages in modern development. Mastering its core functions can significantly improve how you write, read, and maintain code. Top 5 JavaScript functions every developer should know: • map() – Transforms each item in an array and returns a new array, making data manipulation cleaner and more expressive. • filter() – Creates a new array containing only elements that meet a specific condition, improving readability and intent. • reduce() – Condenses an array into a single value (sum, object, array), enabling powerful data aggregation patterns. • forEach() – Iterates over an array to perform side effects like logging or updating values without returning a new array. • find() – Returns the first element that satisfies a condition, ideal for quick lookups in collections. A few other essential JavaScript functions to explore are: • some() • every() • includes() • sort() • concat() Understanding these functions isn’t just about syntax—it’s about writing clearer, more intentional JavaScript. #JavaScript #JS #WebDevelopment #Frontend #FullStack #Programming #SoftwareDevelopment #CodingTips
To view or add a comment, sign in
-
-
🚀 Just published: The JavaScript Variable Declaration Trilogy After years of writing JavaScript, I decided to go beyond the usual "use const by default" advice and explore the why behind var, let, and const. In this deep dive, I cover: ✅ The Temporal Dead Zone (and why it catches bugs you didn't know you had) ✅ The closure gotcha that's bitten every JS developer at least once ✅ Why const doesn't mean immutable (and what it actually protects) ✅ Performance implications nobody talks about ✅ Real-world horror stories and how let/const solve them This isn't another surface-level comparison it's about building the right mental models to write bulletproof JavaScript. Full breakdown with visual walkthroughs 👇 https://lnkd.in/ehQs6Nbf #JavaScript #WebDevelopment #Programming #ES6 #SoftwareEngineering #CodingTips #FrontendDevelopment
To view or add a comment, sign in
-
Most developers don’t struggle with JavaScript. They struggle with "this". And honestly… that’s fair. Because this is not about where code is written. It’s about: • How a function is defined • How it is called • What execution context it runs in After breaking down strict mode, browser vs Node behavior, arrow functions, IIFEs, and nested execution contexts — I finally structured everything into one mental model. I wrote a deep dive covering: - Execution Context - Call-site Rules - Arrow vs Normal Functions - Strict Mode Differences - ES Modules vs CommonJS - 22-step Output Prediction Challenge If you can predict every output in the final challenge, you’ve mastered this. #JavaScript #WebDevelopment #Frontend #Programming #SoftwareEngineering #NodeJS #ES6 #Coding
To view or add a comment, sign in
-
Today I finally understood something that confused me for a long time in JavaScript 👇 “JavaScript uses prototypal inheritance.” At first, it sounded confusing. But once I focused on how property lookup actually works, things started to click. Here’s the key realization for me: ✅ JavaScript doesn’t copy properties ✅ It delegates property access through the prototype chain ✅ If a property isn’t found on an object, JS looks “somewhere else” — its prototype Understanding this made concepts like: ✔ __proto__ vs prototype ✔ constructor functions ✔ ES6 classes ✔ built-in methods feel much clearer. I wrote a short blog explaining prototypal inheritance from a learner’s perspective, with simple examples and diagrams 👇 🔗 https://lnkd.in/ghBSBg5R If you’re also learning JavaScript, this might help you too 🙂 Hitesh Choudhary Piyush Garg Chai Aur Code Akshay Saini 🚀 #javascript #learninginpublic #webdevelopment #frontend #programming
To view or add a comment, sign in
-
Hi Developers😊, Recently, I was working on refactoring static mapping inside handlers, faced a common JavaScript error saying “Cannot access before initialization”, and it took some time to understand what was really going on. The root cause turned out to be a circular dependency. I was using a dispatcher/registry pattern where the registry imported handlers and one of the handlers imported the registry back. eg. A imports B and B imports A A->B->A (TDZ zone) This created a loop where both files were waiting for each other to be initialized, and Node.js couldn’t resolve it. The fix I got was to keep dependencies in one direction only. Handlers should not know about the registry which means never import registry inside handlers let dispatcher do the same. Sharing this in case it helps someone save some debugging time like it did for me. Thanks for the reading📖 #NodeJS #JavaScript #Backend #Learning #CleanCode #refactoring
To view or add a comment, sign in
-
𝗧𝗵𝗲 𝗝𝗮 v𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗘𝗫𝗲𝗰𝘂𝘁𝗶𝗼𝗻 𝗖𝗼𝗻𝘁𝗲𝗫𝘁 You write code and hit "run". But what happens next? The JavaScript engine creates an Execution Context. This is the environment where your code runs. It holds variables, functions, and the scope chain. Think of it as a container that stores everything your code needs. The engine pre-scans your code before running it. It allocates memory, sets variables to undefined, and maps out the scope chain. Then it runs your code line by line. Here's an example: ``` is not allowed, so let's describe it: You have a variable devName and two functions: startSprint and displayTask. When startSprint is called, it creates a new context. When displayTask is called, it creates another context. The Call Stack is like a to-do list. It's a last-in, first-out structure. When a function finishes, its context is removed from the stack. Understanding the Execution Context helps you debug your code. It explains how closures work and how to improve performance. You can think of the Global Context like the main branch of your repo. Function contexts are like feature branches or sandboxes. The Execution Context is the key to understanding JavaScript. It's the "why" behind many weird behaviors. Once you understand it, debugging becomes easier. Source: https://lnkd.in/ghTAE-4q
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
Curious to know why let has to be hoisted if it cannot be used in the TDZ? Or it is a default behavior of js?