JavaScript Notes — Execution Context, Hoisting, Closures While revising JavaScript fundamentals, I wrote down a few clear notes about how the engine actually executes code. Execution Context When a JavaScript program runs, the engine creates an Execution Context. 1️⃣ Global Execution Context (GEC) This is created first when the program starts. 2️⃣ Function Execution Context (FEC) Whenever a function is called, JavaScript creates a new execution context for that function. The flow looks something like this: Global Context → Function Context → Nested Function Context → … Each function call adds a new context to the call stack, and it is removed once execution finishes. Parts of an Execution Context Every execution context contains four main components: 1. Variable Environment Stores variables and function declarations defined inside the current execution context. 2. Lexical Environment Represents the scope chain. It determines how JavaScript resolves variables by checking outer scopes. Example chain: Global Scope → Function Scope → Inner Function Scope → … 3. this Binding Represents the current execution context object. In browsers (global scope), this usually refers to the window object. 4. Outer Environment Reference Points to the parent lexical environment, which allows JavaScript to access variables from outer scopes. In function contexts, this environment also includes the arguments object, which is an array-like structure containing the arguments passed to the function. Hoisting Hoisting is how JavaScript handles variable and function declarations during the creation phase of execution. What actually happens: Declarations are registered in memory before code execution. Variables declared with var are initialized as undefined. Example: console.log(a); // undefined var a = 10; The engine internally interprets it roughly like this: var a; console.log(a); a = 10; Closure A closure happens when an inner function can access variables from its outer function even after the outer function has finished executing. This works because the inner function retains a reference to the lexical environment where it was created. Scope Scope simply defines where a variable exists and where it can be accessed. Common types: Global Scope Function Scope Block Scope (let / const) These are not “advanced tricks.” They are core mechanics of how the JavaScript engine works. If you don’t understand execution context, hoisting, and closures, debugging JavaScript becomes guesswork instead of reasoning. Currently revising fundamentals alongside DSA practice to strengthen both problem-solving and JavaScript internals. #JavaScript #WebDevelopment #FrontendDevelopment #Programming #JavaScriptFundamentals #ExecutionContext #Closures #Hoisting #Developers #BuildInPublic #CodingJourney #TechLearning
JavaScript Execution Context, Hoisting, Closures Explained
More Relevant Posts
-
Understanding the JavaScript Event Loop While learning Angular, I revisited a core concept I had taken for granted: the event loop. This concept explains several important behaviors in JavaScript: - Why async code behaves “out of order.” - Why Promises run before setTimeout. - How frameworks know when to update the UI. I’ve broken it down with simple mental models and real examples. #JavaScript #Angular #WebDevelopment #EventLoop
To view or add a comment, sign in
-
Most developers learn JavaScript… but very few actually understand how it works under the hood. Lately, I’ve been diving deep into concepts from JavaScript Hard Parts, and honestly… it completely changed how I see functions. At first, I thought a function is just: ➡️ Input → Process → Output But it turns out… that’s only half the story. Every time a function runs, JavaScript creates a new execution context → a fresh memory space that gets wiped out after execution. That’s why functions don’t “remember” anything between calls… right? Well… not always. Here’s where things get interesting 👇 When you define a function inside another function, JavaScript does something powerful and hidden: It doesn’t just store the function’s code… It also stores a link to the data around it at the moment it was created. That hidden link is what we call: 👉 Closure Think of it like this: Every function has a backpack 🎒 Inside it, there’s data from where it was defined (not where it’s called). So when the function runs later: It first checks its local memory If not found… it opens its backpack And uses that stored data And here’s the real game-changer: 🔥 Functions in JavaScript have TWO types of memory: Temporary memory → created on every run (and deleted) Persistent memory → stored in the closure (and stays alive) Even more interesting… Every time you call a function that returns another function: ➡️ You create a completely new closure Which means: Different functions Different private data Same logic… different memory Why does this matter? Because this concept powers a LOT of real-world patterns: ✅ Private variables (data hiding) ✅ Memoization (performance optimization) ✅ Module pattern (clean architecture) ✅ Async callbacks & API handling ✅ Iterators & generators The biggest mindset shift for me was this: ❌ Data access is NOT based on where a function is executed ✅ It’s based on where the function is defined (Lexical Scope) This one concept alone explains a huge part of how JavaScript really works. And once it clicks… you stop writing code that “just works” and start writing code that’s intentional, optimized, and scalable. Still learning… but this was one of those “aha” moments I had to share. If you’re learning JavaScript, don’t skip this part. It’s not just theory… it’s the foundation of everything. #JavaScript #Frontend #WebDevelopment #Programming #Closure #CleanCode #SoftwareEngineering
To view or add a comment, sign in
-
-
Are you still using traditional string concatenation in JavaScript? It works… but it quickly becomes messy and hard to maintain. In this article, I break down how Template Literals simplify your code with: • Cleaner syntax • Embedded variables & expressions • Multi-line strings • Practical modern use cases If you're learning or working with JavaScript, this is a must-know concept. Read here 👉 https://lnkd.in/gHEZrAhX #JavaScript #Programming #WebDevelopment #Frontend #Coding
To view or add a comment, sign in
-
🚀 Understanding the JavaScript Event Loop (Clearly & Practically) | Post 2 JavaScript is single-threaded — yet it handles asynchronous tasks like a pro. The secret behind this is the Event Loop 🔁 --- 📌 What is the Event Loop? The Event Loop is a mechanism that continuously checks: 👉 “Is the Call Stack empty?” If yes, it pushes pending tasks into execution. --- 🧩 Core Components 🔹 Call Stack Executes synchronous code line by line. 🔹 Web APIs (Browser / Node.js) Handles async operations like: - setTimeout - API calls - File operations 🔹 Callback Queue Stores callbacks once async tasks are completed. 🔹 Event Loop Moves callbacks from the queue to the Call Stack when it's free. --- 🔁 How It Works 1. Execute synchronous code 2. Send async tasks to Web APIs 3. Once done → push to Callback Queue 4. Event Loop checks → moves to Call Stack --- 🧠 Example console.log("Start"); setTimeout(() => { console.log("Async Task"); }, 0); console.log("End"); 👉 Output: Start → End → Async Task Even with "0ms", async tasks wait until the stack is empty. --- ⚡ Important Concept 👉 Microtasks vs Macrotasks ✔️ Microtasks (High Priority) - Promise.then - async/await ✔️ Macrotasks - setTimeout - setInterval 📌 Microtasks always execute before macrotasks. --- 🎯 Why You Should Care Understanding the Event Loop helps you: ✅ Write non-blocking, efficient code ✅ Debug async behavior easily ✅ Build scalable applications ✅ Crack JavaScript interviews --- 💬 Mastering this concept is a game-changer for every JavaScript developer. #JavaScript #EventLoop #WebDevelopment #NodeJS #Frontend #Programming #SoftwareEngineering
To view or add a comment, sign in
-
-
When I started learning JavaScript, async code felt unpredictable. Things didn’t execute in order. Logs appeared out of nowhere. And promises felt like “magic”. The real issue? I didn’t understand callbacks. Everything in async JavaScript builds on top of them. So I wrote this article to break it down clearly: 👉 Execution flow 👉 Sync vs async callbacks 👉 Why they still matter in modern code If async JS has ever felt confusing, this will help. https://lnkd.in/g7DJ7yXX #JavaScript #LearningToCode #Callbacks #SoftwareDevelopment
To view or add a comment, sign in
-
💡 Understanding Closures in JavaScript (Simple & Clear) Closures are one of the most powerful concepts in JavaScript — and also one of the most confusing at first! 👉 A closure is created when a function remembers variables from its outer scope, even after the outer function has finished executing. 🔹 Example: function outer() { let count = 0; return function inner() { count++; console.log(count); }; } const counter = outer(); counter(); // 1 counter(); // 2 counter(); // 3 👉 Let’s break what’s really happening: • The outer() function runs and creates a variable count • It creates the inner() function • outer() returns inner() (not calling it, just returning it) ⚠️ Normally: When a function finishes execution, its variables are destroyed. ✅ But here: inner() is still using count 👉 So JavaScript keeps count in memory 👉 This preserved memory is called a closure 💡 Important insights: • Functions in JavaScript are first-class (can be returned and stored) • inner() runs later, not inside outer() • It keeps a reference to count, not a copy • That’s why the value updates (1 → 2 → 3) 🔥 Closure in Action (Tricky Example): for (var i = 1; i <= 3; i++) { setTimeout(function() { console.log(i); }, 1000); } 👉 Output: 4 4 4 ❓ Why? • var is function-scoped (only one shared variable i) • Loop finishes first → i becomes 4 • All callbacks use the same i ✅ Fix using let: for (let i = 1; i <= 3; i++) { setTimeout(function() { console.log(i); }, 1000); } 👉 Output: 1 2 3 ✔ Because: • let is block-scoped • Each iteration gets its own i • Each callback closes over a different variable ✅ Why closures are useful: • Data privacy (private variables) • Maintaining state • Used in callbacks and async programming 📌 One-line takeaway: A closure is a function that remembers its outer variables even after the outer function has finished execution. #JavaScript #WebDevelopment #Frontend #Coding #LearnToCode
To view or add a comment, sign in
-
-
🚀 Mastering Closures in JavaScript – A Real-World Example One of the most powerful (and often misunderstood) concepts in JavaScript is the closure. Think of it as a backpack 🎒 that an inner function carries, filled with variables from its outer function—even after the outer function has finished running. Here’s a neat example: function logWithPrefix(prefix: string): (message: string) => void { // Inner function remembers 'prefix' return function (message: string) { log(`${prefix} | ${message}`); }; } // Create loggers with different "backpacks" const infoLogger = logWithPrefix('INFO'); const errorLogger = logWithPrefix('ERROR'); infoLogger('Hello World!'); // Output: "INFO | Hello World!" errorLogger('Something went wrong!'); // Output: "ERROR | Something went wrong!" function log(message: string): void { console.log(message); } 💡 What’s happening here? logWithPrefix creates a closure. The inner function remembers the prefix variable, even after logWithPrefix has returned. This allows us to build reusable, context-aware loggers (INFO, ERROR, etc.) without repeating code. 👉 Closures are everywhere: event handlers, callbacks, and even frameworks like React rely on them. Once you grasp this, you unlock a new level of JavaScript power. 🔑 Takeaway: Closures = memory + reusability + cleaner code. ✨ If you found this useful, imagine how closures can simplify your next project. Keep experimenting, and you’ll see them pop up more often than you think! #JavaScript #TypeScript #Closures #WebDevelopment #CleanCode #InterviewPrep #LearningEveryday #TechLeadership
To view or add a comment, sign in
-
-
🧠 How JavaScript Handles Memory (Simple Explanation) Most developers write JavaScript daily… but very few understand how memory works behind the scenes. And this is exactly why memory leaks happen. 👀 ✅ 1️⃣ Memory Allocation When you create variables, JavaScript automatically allocates memory: let name = "Angular"; let user = { id: 1 }; let nums = [1, 2, 3]; JavaScript stores them in memory without you doing anything. ✅ 2️⃣ Stack vs Heap (Very Important) 🟢 Stack Memory Stores primitive values: number string boolean null undefined Fast and simple. let a = 10; let b = a; b = 20; console.log(a); // 10 Because stack stores copy of value. 🔵 Heap Memory Stores objects and arrays. let obj1 = { name: "Test" }; let obj2 = obj1; obj2.name = "Frontend Dev"; console.log(obj1.name); // Frontend Dev 😬 Because heap stores reference, not copy. ✅ 3️⃣ Garbage Collection (GC) JavaScript automatically removes unused memory. If a value is not reachable, it gets deleted. Example: let user = { name: "Ali" }; user = null; Now the object becomes unreachable → GC removes it. ⚠️ Common Cause of Memory Leaks 🚨 Unremoved Event Listeners button.addEventListener("click", () => console.log("clicked")); If you never remove it, memory keeps growing. 🎯 Why This Matters (Especially in Angular) Understanding memory helps you: ✔ Avoid memory leaks ✔ Improve performance ✔ Write scalable applications ✔ Handle subscriptions properly (RxJS) 💡 Rule for Angular developers: Always unsubscribe or use async pipe. #JavaScript #Angular #Frontend #WebDevelopment #Performance #Programming
To view or add a comment, sign in
-
-
JavaScript's tooling chaos might finally be over. One release just changed everything. 🔧 For years, front-end developers have juggled a fragmented mess: a bundler here, a linter there, a test runner somewhere else, a package manager fighting everything. The JavaScript ecosystem's famous "fatigue" has been real — until now. Evan You just announced Vite+, described as "a unified toolchain for JavaScript." One CLI. One config. Runtime, package manager, bundler, linter, formatter, and test runner — all unified. And it's built on Oxc and Rolldown, the Rust-powered tools that are rewriting what "fast" means for developers. But that's just the start. Here's everything dropping in the JavaScript/TypeScript ecosystem right now: 🚀 Vite 8.0 is out — Bundles now run on Rolldown, delivering dramatically faster builds. Integrated Devtools, native tsconfig paths support, and Wasm SSR are all built in from day one. ⚡ TypeScript just got turbocharged — Microsoft's "Project Corsa" ports the TypeScript compiler to Go. Benchmark result: the VS Code codebase compiles in 7.5 seconds vs. 77.8 seconds before. That's a 10× speedup. Your IDE will feel like a different tool. 🟢 Node.js runs TypeScript natively — Node 23.6 and 22.18 enable TypeScript execution via "Type Stripping" by default. No more ts-node, no more build steps just to run a script. 🎯 Oxfmt hits beta — Passes 100% of Prettier's test suite while running up to 36× faster. Formatting is no longer a bottleneck in your CI pipeline. 🏗️ Vite+ is the endgame — One command to bootstrap, build, lint, test, and ship. If it delivers on its promise, we're looking at the biggest DX leap since npm itself. For teams spending hours on tooling configuration, these releases represent real savings. For individual developers, they mean less context-switching and more time building actual features. The Rust-ification of JavaScript tooling is in full swing — and it's delivering. 💬 Which of these changes your workflow the most: Vite+, native TypeScript in Node.js, or the 10× compiler speedup? I'm curious what teams are most excited about. #JavaScript #TypeScript #WebDevelopment #DevTools #Vite #NodeJS #FrontendDevelopment
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
Awesome