JavaScript Lexical Scope Explained

🏠 Lexical Scope in JavaScript Think of your code like a house with rooms. 🌍 The whole house = Global Scope 🏠 Each room = A Function 🚪 A room inside another room = Nested Function Now here’s the important rule: 👉 Inner rooms can see outside. 👉 But outside rooms can’t see inside. Let’s understand using the image: 🌍 Global Scope (Outside the house) let hero = "Alice"; 🏠 Outer Function (First room) let spell = "Fire"; 🚪 Inner Function (Room inside room) let mana = 50; console.log(hero); // ✅ Can access (Global) console.log(spell); // ✅ Can access (Outer) console.log(mana); // ✅ Its own variable ✔ Inner function can access: Its own variables Parent function variables Global variables But if the outer function tries this: console.log(mana); // ✖️ Error It fails. Because outer cannot access inner’s variables. 🔑 Simple Rule to Remember: A function can use variables from: 🏠 Its own room ⬆ Parent rooms 🌍 Global But it cannot look inside child rooms. #javascript #typescript #reactjs #nextjs #frontend_developer #react_developer #web_Developer #scope #laxical

  • diagram

To view or add a comment, sign in

Explore content categories