Hoisting in JavaScript Hoisting is a JavaScript mechanism where variable and function declarations are moved to the top of their containing scope during the compilation phase, before the code is executed. This means that you can use variables and functions before they are declared in the code. When JavaScript code runs, it’s not executed line by line immediately. The engine scans the code before running it. It creates something called a variable environment for each scope. During this creation phase, it: Registers all variable and function declarations Sets up memory bindings for them inside that scope Execution phase — actually runs the code line by line Hoisting happens during the creation phase, before any code executes. // Creation Phase (before execution) Memory Environment: a → undefined // var declaration found // Execution Phase console.log(a); // reads 'undefined' a = 10; // assigns new value TDZ is the period between the start of a scope and the point where a let or const varia https://lnkd.in/gc3k5ZaJ
Understanding JavaScript Hoisting: A Key Concept
More Relevant Posts
-
💡 Do you know the shortest program in JavaScript? Yes — it’s an empty file! Even if there’s literally nothing in your JS file, the JavaScript engine still does important work behind the scenes. Here’s why: 1️⃣ Global Execution Context is Created JS first sets up a Global Execution Context (GEC). This is the space where global variables live, functions are defined, and the global object is connected. 2️⃣ Global Object is Initialized Browser: window → contains console, document, alert, setTimeout… Node.js: global → contains process, Buffer, require, setTimeout… This object is the foundation for all code, even if the file is empty. 3️⃣ this Refers to the Global Object Inside the global context: Browser → this === window Node → this === global Example: console.log(this); // window (browser) or [Object: global] (Node) 4️⃣ No Code = No Execution, But Environment Exists The engine checks for statements to run. If the file is empty, nothing executes — but all the setup has already happened. ✅ Takeaway: The program is syntactically valid (no errors) It’s functionally empty (nothing runs) Global environment is initialized (GEC, global object, this)
To view or add a comment, sign in
-
-
Think you know JavaScript hoisting? The usual line: “variables and functions are moved to the top,” misses the deeper reason why. To truly understand hoisting, you need to look at how JavaScript executes code. Every execution context runs in two phases: 1. Memory Creation Phase: Before any code runs, JavaScript enters the memory creation phase. It scans through your file and allocates memory for all variables and function declarations. Variables are assigned undefined, while function declarations are fully copied into memory. That’s why you can access variables (though they’ll be undefined) and call functions before they’re declared. 2. Code execution phase: Only after memory allocation does JavaScript start running your code line by line. Hoisting isn’t about JavaScript moving code around; it’s the result of its two-phase execution model. Understanding this provides a much deeper insight into how JavaScript works under the hood. If you want to explore this further, I highly recommend Akshay Saini’s “Namaste JavaScript” series: https://lnkd.in/d8qZ_PSV — It explains these concepts clearly and practically.
To view or add a comment, sign in
-
🌀 𝗠𝗮𝘀𝘁𝗲𝗿𝗶𝗻𝗴 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗣𝗿𝗼𝘅𝗶𝗲𝘀 — 𝗜𝗻𝘁𝗲𝗿𝗰𝗲𝗽𝘁, 𝗖𝗼𝗻𝘁𝗿𝗼𝗹 & 𝗣𝗼𝘄𝗲𝗿 𝗨𝗽 𝗬𝗼𝘂𝗿 𝗢𝗯𝗷𝗲𝗰𝘁𝘀 Wrappers, traps, handlers — the native Proxy object in JavaScript gives you 𝗺𝗲𝘁𝗮-𝗰𝗼𝗻𝘁𝗿𝗼𝗹 over how your objects behave. Want to intercept property access, validate assignments, or log operations? Proxies unlock that power. In this post I break down: ✅ What Proxy objects really do (the target + handler + traps model) ✅ How traps like `get`, `set`, `apply`, `construct` let you intercept reads, writes, function calls and constructor calls ✅ Real-world use cases: validation, access control, logging, lazy initialization, smart defaults 👉 Read here: https://lnkd.in/d2z-7z6w Stay curious. Code smarter. 🧠 #JavaScript #WebDevelopment #Proxies #Metaprogramming #CodingTips
To view or add a comment, sign in
-
🚀 Day 2: Dive Deep — JavaScript Hoisting Before your code runs, JavaScript secretly does a quick setup behind the scenes — this process is called Hoisting. In this phase, JavaScript scans your code and creates memory space for all variables and functions even before execution starts. ✨ What happens: Function declarations are fully stored in memory — you can call them even before they appear in the code. Variables (declared using var) are also lifted to the top, but only their names are stored — their values are set as undefined until the actual assignment happens. So when you see undefined before a variable is initialized, it’s not an error — it’s JavaScript saying, “Hey, I know this variable exists, but I haven’t given it a value yet!” Hoisting shows how JavaScript prepares your code in advance — setting the stage before the show begins. 🔥 Key takeaway: JavaScript doesn’t run line by line right away — it first creates memory for everything, marks variables as undefined, and then executes step by step. Understanding this tiny detail helps you debug smarter and truly see what’s happening behind the scenes.
To view or add a comment, sign in
-
-
Understanding Hoisting in JavaScript: A Simple Guide JavaScript Hoisting 🔹 What is Hoisting? In simple terms: Using var Variables declared with var are hoisted to the top of their scope and are initialized with a value of undefined. This means you can access the variable before its declaration without an error, but its value will be undefined until the assignment is made. Example: code: console.log(myVar); // Outputs: undefined var myVar = "Hello, World!"; console.log(myVar); // Outputs: "Hello, World!" How JavaScript sees it: var myVar; // Declaration is hoisted and initialized as undefined console.log(myVar); myVar = "Hello, World!"; // Initialization happens here console.log(myVar); Using let and const Variables declared with let and const are also hoisted, but they are not initialized with a default value. Accessing a let or const variable before it is declared will result in a ReferenceError. This is due to the Temporal Dead Zone (TDZ), which is the time from t https://lnkd.in/gtrzXDfW
To view or add a comment, sign in
-
Ever wondered why var, let, and const behave so differently in JavaScript ? You might think JS just runs top to bottom — but it actually prepares everything first before execution. Let’s talk about that invisible magic called Hoisting 👇 🧠 What is Hoisting ? Most people think hoisting means JavaScript “moves” your code to the top. But that’s not actually true. It’s more like JavaScript doing some preparation before execution. When your JS file runs, the engine doesn’t just go line by line right away — it first scans the entire code, and during this phase, it allocates memory for all your variables and functions before any line is executed. Here’s what actually happens: ✅ Function declarations → fully stored in memory (you can call them before they appear). ⚠️ Var variables → stored but initialized with undefined. 🚫 Let and Const → stored too, but they’re not “activated” yet. That “not activated yet” period is called the Temporal Dead Zone (TDZ) — a phase where the variable exists in memory, but you can’t access it until its declaration line executes.
To view or add a comment, sign in
-
-
Event Loop, Synchronous & Asynchronous JavaScript (Simple & Clear) JavaScript runs on a single thread, but still handles background tasks like timers and API calls without blocking. This is possible because of the Event Loop, which runs all synchronous code first and then executes asynchronous callbacks when the main thread is free. 🟦 Synchronous JavaScript Synchronous code runs line by line. Each statement waits for the previous one to finish. ✅ Program console.log("Start"); console.log("Processing..."); console.log("End"); ▶️ Output: Start Processing... End 🟩 Asynchronous JavaScript Asynchronous tasks don’t block the main thread. Functions like setTimeout() run in the background and return results later. ✅ Program console.log("Start"); setTimeout(() => { console.log("Async Task Done"); }, 2000); console.log("End"); ▶️ Output: Start End Async Task Done // after 2 seconds
To view or add a comment, sign in
-
💡 Cracking the Code: JavaScript's Lexical Scope & Scope Chain Ever wonder exactly how an inner function knows where to find a variable defined outside of it? Master Lexical Scope and the Scope Chain to unlock the true power of JavaScript, especially Closures! 1️⃣ Lexical Scope (The "Where You Live" Rule) Lexical scope (or Static Scope) is perhaps the most fundamental concept: Definition: Variable access is determined by where the code is physically written, not where the function is executed or called from. The Key: The surrounding code is "frozen" at definition time. Example: If function inner() is written inside function outer(), inner will always look to outer for variables, regardless of where inner() is later invoked. 2️⃣ The Scope Chain (The Lookup Path) The Scope Chain is the variable resolution mechanism that JavaScript uses at runtime: It defines the specific path the engine takes to find the value of a variable. The Lookup Order: The search always starts locally and moves outward: Current Scope ---> Parent Scope ---> Global Scope In Action: If you have level3 nested inside level2, which is nested inside level1, the function level3 can access variables defined in level1 by traversing this chain. 3️⃣ The Closure Connection 🔗 This is where the magic happens! Formula: Lexical Scope + Scope Chain = Closures Because of lexical scope, an inner function maintains a "memory" of its parent's variables even after the parent function has finished executing. This ability to "remember" is a closure!
To view or add a comment, sign in
-
-
Going back to basics 🌱 How Javascript executes your code inside the JS Engine ? Let’s say you have a "landing page" that needs a bit of interactivity maybe a "button click". So, you add a JavaScript file to make it all work smoothly. Now, these are are steps that will occure behind the scene - 1. The "Javascript engine" first reads your code from top to bottom, checking if there are any "syntax errors". Then it converts the code into a structured format called an "Abstract Syntax Tree (AST)" basically something the computer can understand. 2. Interpretation : This is where the Javascript engine’s interpreter (like "Ignition" in Chrome’s V8 engine) turns your code into "bytecode" for faster execution. (No need to stress about these , just know this step helps your code run faster, we will explore it more later.) 3. Optimization (JIT) : If you remember, we already discussed "Just-in-time (JIT)" Compilation in an earlier post that’s exactly what happens here. While your page is running, the Javascript engine keeps an eye on which parts of your code run frequently for example, a function that executes every time a button is clicked. When it notices such patterns, the JIT Compiler steps in and converts those parts into machine code, so the next time they run, it happens much faster. 4. Execution : Now, whenever you interact with your page like "clicking a button", the engine runs the already optimised machine code directly. That’s how things happen when you add Javascript to your page. But...but..but , if there is no Javascript file, will the JavaScript engine still work???? #Javascript #Frontend
To view or add a comment, sign in
-
-
🔹 Functions in JavaScript — The Building Blocks of Reusable Code A function in JavaScript is a block of code designed to perform a specific task. It helps make your code modular, reusable, and maintainable. 🧩 Definition: A function is a set of statements that performs a particular operation and can be executed whenever it is called. 🔸 Types of Functions 1. Named Function or Function Declaration 2. Anonymous Function or Function Expression 3. Arrow Function 4. IIFE (Immediately Invoked Function Expression) 🔸 Function Parameters and Arguments Parameters: Variables listed in the function definition. Arguments: Values passed to the function when called. 🔸 Scope and Function Behavior Functions have access to: Local Scope: Variables declared inside the function. Global Scope: Variables declared outside the function. Lexical Scope: Inner functions can access variables of their parent function. 🔸 Advantages of Using Functions ✅ Reusability ✅ Modularity ✅ Easy Debugging ✅ Code Organization
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