Ever wondered what actually happens behind the scenes when JavaScript runs your code? 🤔 How Variables & Functions Work Behind the Scenes in JavaScript Today I focused on understanding what actually happens inside the JavaScript engine when we write variables and functions — and it completely changed how I read JS code. 🧠 Step 1: JavaScript Creates an Execution Context Before executing any code, JavaScript creates an Execution Context. This happens in two phases: 1. Creation Phase (Memory Allocation Phase) In this phase, JavaScript scans the entire code before running it and prepares memory. ✔ Variables var variables are allocated memory and initialized with undefined let and const are also allocated memory, but they stay in the Temporal Dead Zone (TDZ) until initialized ✔ Functions Function declarations are stored fully in memory (function body included) Function expressions & arrow functions behave like variables and depend on var / let / const 👉 This is the real reason hoisting exists. 2.Execution Phase (Code Runs Line by Line) Now JavaScript starts executing the code: Variables get their actual values Functions are executed when they are called A new Function Execution Context is created for every function call Each context is pushed to the Call Stack After execution, it is removed from the stack Why Functions Can Be Called Before Declaration? because function declarations are fully hoisted during the creation phase. 💡 Key Takeaways JavaScript doesn’t execute code directly — it prepares first Hoisting is a byproduct of the creation phase var, let, and const differ because of how memory is allocated Understanding execution context makes debugging much easier. Mastering the basics is what truly levels up a developer. Thanks to Anshu Pandey and Sheryians Coding School #JavaScript #JavaScriptbasics #ES6 #JSEngine #coding
JavaScript Execution Context: Variables & Functions
More Relevant Posts
-
💡 Understanding the JavaScript Event Loop (Made Simple) When I started learning JavaScript, I was confused about how setTimeout, button clicks, and API calls worked — especially since JavaScript is single-threaded. This visual really helped me understand what happens behind the scenes: 👉 1. Call Stack – Runs code line by line (synchronous code) 👉 2. Web APIs – Handles async tasks like timers and fetch requests 👉 3. Callback Queue – Stores completed async callbacks 👉 4. Event Loop – Moves callbacks to the stack when it’s empty 🔎 Simple Example: console.log("Start"); setTimeout(() => { console.log("Inside Timeout"); }, 0); console.log("End"); 👉 What do you think the output will be? The output is: Start End Inside Timeout Even though the timeout is set to 0 milliseconds, it doesn’t run immediately. Here’s why: 1️⃣ "Start" goes to the call stack → executes 2️⃣ setTimeout moves to Web APIs 3️⃣ "End" executes 4️⃣ The callback moves to the queue 5️⃣ The Event Loop waits until the stack is empty 6️⃣ Then it pushes "Inside Timeout" to the stack That’s the Event Loop in action 🚀 Understanding this concept made: ✅ Promises easier ✅ Async/Await clearer ✅ Debugging smoother If you're learning JavaScript, mastering the Event Loop is a big step forward. #JavaScript #WebDevelopment #BeginnerDeveloper #AsyncProgramming #FrontendDevelopment #mernstack #fullstack
To view or add a comment, sign in
-
-
🚀 Day 75 — Visualizing the JavaScript Call Stack Today I learned how JavaScript actually executes code behind the scenes using something called the Call Stack. Understanding this completely changed how I think about function execution. 🧠 What is the Call Stack? The Call Stack is a mechanism used by JavaScript to keep track of function execution. 👉 JavaScript is single-threaded, meaning it executes one task at a time. So whenever a function runs, it is added to the stack. 🔹 How It Works Think of it like a stack of plates: ✅ New function → placed on top ✅ Function finished → removed from top This follows the rule: LIFO (Last In, First Out) 🔍 Example function third() { console.log("Third function"); } function second() { third(); console.log("Second function"); } function first() { second(); console.log("First function"); } first(); ⚙ Execution Flow (Step by Step) 1️⃣ first() added to Call Stack 2️⃣ second() added 3️⃣ third() added 4️⃣ third() executes → removed 5️⃣ second() executes → removed 6️⃣ first() executes → removed Finally → Stack becomes empty ✅ 📌 Why Call Stack Matters Understanding Call Stack helps explain: ✅ Function execution order ✅ Debugging errors ✅ Stack Overflow errors ✅ Infinite recursion problems ✅ Async behavior understanding ⚠ Example of Stack Overflow function repeat() { repeat(); } repeat(); Since the function never stops, the stack keeps growing until: ❌ Maximum Call Stack Size Exceeded 💡 Key Learning JavaScript doesn’t randomly run code. Every function waits its turn inside the Call Stack, making execution predictable and structured. Understanding this made debugging much easier for me. #Day75 #JavaScript #CallStack #WebDevelopment #LearningInPublic #DeveloperJourney
To view or add a comment, sign in
-
-
Day 6: I learned how JavaScript actually runs code, and it makes lot of sense At first, it was a little confusing, but I’ve come to understand the main concepts and how they work. First thing I learned: Execution Context Every JavaScript program runs inside an execution context. It’s a dedicated workspace where your code is executed. Within that space, JavaScript keeps track of the variables that are defined, what other scopes are accessible, and what "this" refers to at that particular moment. I can also say, execution context is a box where your code gets set up and executed. Every time JavaScript runs code, it creates one. Inside that box, three things exist: - Variable Environment: where all your variables and functions are stored - Scope Chain: determines which variables your code has access to - The "this" keyword: tells your code what object it's currently working with Then there's the Call Stack The call stack is simply JavaScript's way of keeping track of where it is in our code. Every time a function is called, it gets placed on top of the stack. When it finishes, it gets removed. We can get a good illustration of this using stack of plates, the item added most recently is the one removed first. And finally: the Callback Queue When you click a button, it doesn’t run the code right away. Instead, it puts a function in a waiting line called the callback queue. Once the main code (the call stack) is done, the function gets picked up and runs In plain terms; - Code runs in a workspace called the execution context. - JavaScript keeps track of what’s running next using a call stack. - Functions triggered by events wait in line in the callback queue. #JavaScriptJourney #LearningToCode
To view or add a comment, sign in
-
Execution of code in JavaScript Have you ever thought about how JavaScript runs code behind the scenes. JavaScript executes code in two main phases: 1- Memory Creation Phase [i] Memory is allocated to variables and functions [ii] Variables are initialized with undefined 2- Execution Phase [i] Code runs line by line [ii] Values are assigned [iii] Functions are executed To manage function calls, JavaScript uses the Call Stack, which follows the LIFO (Last In, First Out) principle.
To view or add a comment, sign in
-
-
The tale of two dots: Mastering the difference between Spread vs. Rest in JavaScript. 🧐 If you are learning modern JavaScript, the three dots syntax (...) can be incredibly confusing. Depending on where you place them, they either act as the Spread operator or the Rest operator. They look identical, but they do complete opposite jobs. Here is the simplest way to differentiate them. ✅ 1. The Spread Operator (The "Unpacker") Think of Spread as opening a suitcase and dumping everything out onto the bed. It takes an iterable (like an array or an object) and expands it into individual elements. Common Use Cases: Copying arrays/objects (shallow copies). Merging arrays/objects together. Passing elements of an array as separate arguments into a function. ✅ 2. The Rest Operator (The "Gatherer") Think of Rest as taking leftovers on a table and putting them all into one Tupperware container. It does the opposite of spread. It collects multiple separate elements and condenses them into a single array or object. Common Use Cases: Handling variable numbers of function arguments. Destructuring arrays or objects to grab "the rest" of the items. 💡 The Golden Rule to Tell Them Apart It’s all about context. Look at where the dots are used: If it’s used in a function call or on the right side of an equals sign, it’s usually Spread (it's expanding data). If it’s used in a function definition or on the left side of an equals sign (destructuring), it’s usually Rest (it's gathering data). Which one do you find yourself using more often in your daily work? #JavaScript #WebDevelopment #CodingTips #SoftwareEngineering #Frontend
To view or add a comment, sign in
-
-
🚀 JavaScript Magic: Why "Undefined" is actually a Feature, not a Bug! I just had a "Wow" moment diving into the JavaScript Execution Context, and it changed how I look at my code. Ever wondered why you can console.log a variable before you even declare it, and JavaScript doesn't lose its mind? 🤯 🧠 The Secret: Two-Phase Execution When your code runs, JavaScript doesn't just start at line 1. It takes two passes: 1.Memory Creation Phase: JS scans your code and allocates space for all variables and functions. 2. Execution Phase: It runs the code line-by-line. ⚡ The var Behavior (Hoisting) If you use var, JavaScript initializes it as undefined during the memory phase. Result: You can log it early. No error, just a quiet undefined. It’s like the variable is there, but its "suit" hasn't arrived yet. 🛑 The let & const Twist (TDZ) Try the same thing with let or const, and the engine throws a ReferenceError. Why? The Temporal Dead Zone (TDZ). While let and const are also "hoisted," they aren't initialized. They stay in a "dead zone" from the start of the block until the moment the code actually hits the declaration. The Lesson: JavaScript isn't just reading your code; it's preparing for it. Understanding the Execution Context makes debugging feel like having X-ray vision. 🦸♂️ Have you ever been bitten by the Temporal Dead Zone, or do you still find yourself reaching for var out of habit? Let’s discuss! 👇 #JavaScript #WebDevelopment #CodingTips #Frontend #Programming101
To view or add a comment, sign in
-
Ever wondered what happens BEHIND THE SCENES when your JavaScript code runs? 🚀 Let me break it down for you! 👇 ❌ Why variables show "undefined" ❌ How functions get called ❌ What "hoisting" really means ❌ Why my code executes in a certain order Then I learned about EXECUTION CONTEXT, and everything clicked! 💡 Here's what happens when this simple code runs: ``` var a = 10; var b = 20; function greet() { var name = "Alice"; console.log("Hello", name); } greet(); ``` 🔄 THE PROCESS: 1️⃣ MEMORY CREATION PHASE → JavaScript scans the code FIRST → Variables get "undefined" → Functions get their full definition → This is why hoisting works! 2️⃣ EXECUTION PHASE → Code runs line by line → Variables get actual values (a=10, b=20) → Functions are invoked 3️⃣ CALL STACK → Manages execution contexts → Works like a stack of plates (LIFO - Last In, First Out) → Each function call creates a NEW context → When function completes, context is removed 🎯 WHY THIS MATTERS: Understanding execution context helps you: ✅ Debug "undefined" errors easily ✅ Master closures and scope ✅ Write more efficient code ✅ Ace technical interviews ✅ Understand async behavior better I've created a detailed guide with visual diagrams explaining the entire process step-by-step! 📄 Check out the attached document for: • Complete execution flow breakdown • Visual representations • Real code examples • Key takeaways 💬 What JavaScript concept confused you the most as a beginner? Drop a comment below! P.S. If you found this helpful, give it a ❤️ and share with someone learning JavaScript! #JavaScript #WebDevelopment #Programming #LearnToCode #CodingTips #ExecutionContext #CallStack #DeveloperCommunity #SoftwareDevelopment #FrontendDevelopment #JavaScriptTips #CodingForBeginners #WebDevTips #TechLearning
To view or add a comment, sign in
-
🧠 The Call Stack in JavaScript — Simplified JavaScript executes code using something called the call stack. It follows one simple rule: Last In, First Out (LIFO). Every time a function runs, it gets pushed onto the stack, and when it finishes, it gets popped off. Understanding this small concept makes debugging errors like “Maximum call stack size exceeded” much easier. It also helps you truly understand recursion and how JavaScript executes code step by step. Read more here 👉 https://lnkd.in/g2CCpCqs #JavaScript #WebDevelopment #Programming
To view or add a comment, sign in
-
Understanding JavaScript internals completely changed the way I write and think deeply about how it works, which has given me confidence. 🚀 How Objects Work Behind the Scenes in JavaScript In JavaScript, objects are not stored directly in variables the way primitive values are. 👉 Objects(body) live in Heap Memory, and variables only store a reference (address) to that object. What does this mean in practice? When you assign an object to another variable, the reference is copied, not the object itself When you pass an object to a function, the function receives the same reference Any change made using one reference affects the original object let user1 = { name: "Alex" }; let user2 = user1; user2.name = "John"; console.log(user1.name); // John Both variables point to the same memory location in the heap. 🧠 Key Insight: JavaScript objects follow pass-by-reference behavior (reference copy), which is why unintended mutations can happen if we’re not careful. Understanding this concept helped me clearly see: Why shallow copy causes issues Why deep copy is sometimes necessary Why objects behave differently from primitives Once you understand the internals, JavaScript stops feeling magical and starts making sense. Go through the diagram, and you will understand better. Thanks to AKA- Anshu Pandey #JavaScript #Objects #MemoryManagement #JSInternals #WebDevelopment #Learning #FrontendDevelopment #WebDevelopment
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