JavaScript Execution Context, Hoisting, Closures Explained

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

To view or add a comment, sign in

Explore content categories