JavaScript Internals: What Actually Happens with var vs let? Most explanations stop at: • var is function-scoped • let is block-scoped But internally, the difference is deeper. 🔹 Execution Context Creation Phase When JS runs, it creates an Execution Context with: 1️⃣ Variable Environment 2️⃣ Lexical Environment 🔴 How var Works Internally • Stored inside the Variable Environment • Hoisted and initialized with undefined • In global scope, attached to the global object (window in browser) Example: console.log(a); // undefined var a = 10; During memory phase: var a = undefined; 🟢 How let Works Internally • Stored inside the Lexical Environment • Hoisted but NOT initialized • Placed inside the Temporal Dead Zone (TDZ) • Not attached to the global object Example: console.log(b); // ReferenceError let b = 20; Memory is allocated, but access before initialization throws error. 🔥 Key Engine-Level Difference var → Accessible before assignment (value: undefined) → Attached to global object → No block scope let → Hoisted but inaccessible (TDZ) → Block scoped → Not part of global object Understanding this helps in: • Avoiding accidental globals • Preventing hoisting bugs • Writing predictable async code • Debugging production issues JavaScript behavior is not “magic” — it’s execution context design. #JavaScript #FrontendDevelopment #ReactNative #WebDevelopment #ProgrammingInternals
var vs let: Execution Context and Hoisting in JavaScript
More Relevant Posts
-
🚀 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 (Microtasks vs Macrotasks) Consider this code: console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); What’s the output? Many expect: Start Timeout Promise End But actual output is: Start End Promise Timeout Why? Because of the Event Loop. JavaScript handles tasks in two major queues: • Microtasks (Promises, queueMicrotask) • Macrotasks (setTimeout, setInterval) Execution order: 1️⃣ Synchronous code runs first 2️⃣ Microtasks run next 3️⃣ Then Macrotasks Even if setTimeout has 0ms delay, it still waits for the macrotask queue. Understanding this explains: • Why some async bugs feel “random” • Why Promises run before setTimeout • Why UI updates sometimes behave unexpectedly JavaScript isn’t single-threaded chaos. It’s single-threaded with a well-defined event model. Understanding the Event Loop changes how you debug async code. What async behavior confused you the most before learning this? #javascript #frontenddeveloper #webdevelopment #eventloop #softwareengineering
To view or add a comment, sign in
-
-
Today, JavaScript left the browser and talked to the world. For the past few weeks, I've been focused on how JavaScript manages data internally — execution context, closures, state-driven rendering. Today I learned where that data actually comes from. The full pipeline, in plain terms: When a browser requests a website, it first asks DNS to translate a domain name into an IP address. The browser then sends an HTTP request to that address. The server responds. That response travels as a plain string — not an object. This is where JavaScript takes over. fetch() sends the HTTP request and returns a Promise — a placeholder for data that hasn't arrived yet. await pauses execution until it does. .json() converts the string into a usable JavaScript object. From that point, it's just an array — the same render logic I already wrote for my job tracker works without modification. I didn't learn new rendering patterns today. I learned that the array I was hardcoding can come from a server instead. The renderUI() function of now doesn't care where the data came from — filtered, fetched, or local. It just renders what it receives. That's the payoff of state-driven architecture. The data source changes. The render logic doesn't. Still early. Still building from the ground up. #JavaScript #WebDevelopment #HTTP #APIs #LearningInPublic #BackendFirst
To view or add a comment, sign in
-
"Var and functions move to the top of your file" ...but do they? Really? Think about it. Open any JavaScript file right now. Add a console.log before a var declaration. Run it. You get undefined — not an error. Call a function 50 lines before you've even written it. It works. Perfectly. Now try the same thing with let or const. It crashes. ReferenceError. If hoisting truly "moves code to the top" — why doesn't it move let and const too? Because nothing is moving anywhere. That explanation you've been hearing since day one? It's a lie. A convenient, oversimplified lie that every tutorial keeps repeating. The truth is — JavaScript reads your code twice. Yes. Twice. The first time, it doesn't execute anything. It just scans your entire file and quietly builds a memory map. Every var it finds gets stored as undefined. Every function gets stored completely. Every let and const gets stored too — but locked. Untouchable. Frozen until their exact line is reached. The second time, it actually runs your code. Line by line. And because memory was already set up, accessing a var before its declaration doesn't crash — it simply finds undefined sitting there, waiting. Nothing moved to the top. The engine just remembered it before you asked. This process has a name that most JavaScript developers have never properly learned — the Execution Context and its two phases. And once you understand it, JavaScript stops being weird. Closures make sense. Scope chains make sense. Even the this keyword starts clicking. I broke this down with code examples and step-by-step visuals on Medium. Link in comments 👇 #JavaScript #WebDevelopment #Programming #SoftwareEngineering #NodeJS #BackendDevelopment
To view or add a comment, sign in
-
-
✨ 𝗗𝗮𝘆 𝟴 𝗼𝗳 𝗠𝘆 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗝𝗼𝘂𝗿𝗻𝗲𝘆 🚀 Today I explored 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗢𝗯𝗷𝗲𝗰𝘁𝘀 𝗮𝗻𝗱 𝘁𝗵𝗲𝗶𝗿 𝗠𝗲𝗺𝗼𝗿𝘆 𝗠𝗮𝗻𝗮𝗴𝗲𝗺𝗲𝗻𝘁 𝗶𝗻-𝗱𝗲𝗽𝘁𝗵, and learned how objects are actually structured behind the scenes in memory. I discovered that JavaScript objects are stored in the heap, and the variable holds a reference (pointer) in the stack. But what’s more interesting is that internally, objects have different pointers: • 𝗠𝗮𝗽 𝗣𝗼𝗶𝗻𝘁𝗲𝗿 → points to the object’s hidden class (structure and layout of properties) • 𝗣𝗿𝗼𝗽𝗲𝗿𝘁𝗶𝗲𝘀 𝗣𝗼𝗶𝗻𝘁𝗲𝗿 → points to where named properties are stored • 𝗘𝗹𝗲𝗺𝗲𝗻𝘁𝘀 𝗣𝗼𝗶𝗻𝘁𝗲𝗿 → points to indexed elements (used especially in arrays) This explains how JavaScript engines optimize objects for performance and access speed. Understanding these low-level details helps me see JavaScript beyond syntax — it’s helping me understand how things really work under the hood. Building strong fundamentals step by step. #JavaScript #100DaysOfCode #WebDevelopment #LearningJourney #FrontendDevelopment #ComputerScience
To view or add a comment, sign in
-
-
Why do some functions return another function(s) if we can just call the function whenever we need it? At first this feels unnecessary. If a function can already run when we call it, why would we want that function to return another function instead of just executing the logic immediately? The reason is that sometimes we want to create a function that remembers certain information for later use. Instead of passing the same data again and again every time we call a function, we can create a function that already remembers that data and uses it whenever it runs. So in some cases we are not just executing a function — we are creating a new function that carries some context with it. This behavior leads us to an important concept in JavaScript called Closures. A closure happens when a function remembers variables from the scope where it was created, even after that outer function has finished executing. Normally, when a function finishes running, its local variables should disappear. But if another function still references them, JavaScript keeps those variables alive. Closures are widely used in JavaScript for things like: • Creating private variables • Preserving state between function calls • Avoiding unnecessary global variables • Remembering configuration values • Supporting callbacks and asynchronous code In the example attached below, you can see how a function is able to access a variable that technically belongs to an outer scope. This happens because of lexical scoping, where a function remembers the environment in which it was created. Closures might seem like a small concept, but they explain many important patterns in JavaScript. A function in JavaScript doesn’t just carry its code. It also carries the environment where it was created. #javascript #closures #chaicode #chaiaurcode
To view or add a comment, sign in
-
-
💗 Hoisting in JavaScript : In Simple Terms Earlier, I used to wonder: “Where exactly do we use hoisting in real projects?” Later I understood something important - Hoisting is not something we “use.” It’s something that’s already happening. Before running your code, JavaScript scans everything and registers variable and function declarations. Like taking attendance before starting class. That process is called hoisting. Example: console.log(a); //undefined var a = 10; Because internally, JavaScript treats it like: var a; console.log(a); a = 10; Now with let: console.log(b); //This throws an error. let b = 20; Why? Because let and const are hoisted too - but they stay inside something called the "Temporal Dead Zone" until initialization. 💡 Hoisting isn’t a feature we manually use. It’s a mechanism built into JavaScript. Even if we don’t think about it, it’s working behind the scenes every time our code runs. JavaScript isn’t unpredictable. It just follows its own execution rules. #JavaScript #FrontendDevelopment #LearnInPublic #InterviewPrep
To view or add a comment, sign in
-
🧠 Ever wondered how JavaScript keeps track of which function is running? JavaScript uses something called the Call Stack. Think of it like a stack of tasks where functions are added and removed as they execute. 🔹 How the Call Stack Works JavaScript follows a Last In, First Out (LIFO) rule. That means: The last function added to the stack is the first one to finish. Example function first() { second(); } function second() { third(); } function third() { console.log("Hello from third function"); } first(); What happens in the Call Stack 1️⃣ first() is pushed to the stack 2️⃣ second() is called → pushed to the stack 3️⃣ third() is called → pushed to the stack 4️⃣ third() finishes → removed from stack 5️⃣ second() finishes → removed 6️⃣ first() finishes → removed 🔹 Visualising the Stack Call Stack at peak: - third() - second() - first() - Global() Then it unwinds back to the Global Execution Context. 💡 Why This Matters Understanding the call stack helps you understand: - Execution order - Stack overflow errors - Debugging JavaScript - Async behaviour It’s one of the core mechanics of the JavaScript engine. Next post: The Event Loop 🚀 #JavaScript #CallStack #Frontend #WebDevelopment #LearnJS #Programming #LearningInPublic
To view or add a comment, sign in
-
-
💡 Pass by Value vs Pass by Reference in JavaScript (Simple Explanation) If you're learning JavaScript, understanding how data is passed is crucial 👇 🔹 Pass by Value (Primitives) When you assign or pass a primitive type (number, string, boolean, null, undefined, symbol, bigint), JavaScript creates a copy. let a = 10; let b = a; b = 20; console.log(a); // 10 console.log(b); // 20 👉 Changing b does NOT affect a because it's a copy. 🔹 Pass by Reference (Objects) When you work with objects, arrays, functions or date objects, JavaScript passes a reference (memory address). let obj1 = { name: "Ali" }; let obj2 = obj1; obj2.name = "Ahmed"; console.log(obj1.name); // Ahmed console.log(obj2.name); // Ahmed 👉 Changing obj2 ALSO affects obj1 because both point to the same object. 🔥 Key Takeaway Primitives → 📦 Copy (Independent) Objects → 🔗 Reference (Shared) 💭 Pro Tip To avoid accidental changes in objects, use: Spread operator {...obj} Object.assign() Understanding this concept can save you from hidden bugs in real-world applications 🚀 #JavaScript #WebDevelopment #Frontend #Programming #CodingTips
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