Variable Scope
Understand where variables live and die — global scope, function scope, and block scope.
Step 1 of 7
What is scope?
Scope determines where a variable is visible and accessible in your code. When you declare a variable, it doesn't exist everywhere — it only exists within a certain region of your program. If you try to use a variable outside its scope, JavaScript will throw a ReferenceError because it can't see it. Understanding scope is essential for writing bug-free code and is one of the most important concepts in programming.
Think of it this way: Scope is like rooms in a house. A variable declared in the kitchen (inside a function) is only visible in the kitchen. But a variable declared in the hallway (outside all functions, at the top level) can be seen from any room. You can't grab something from the bedroom while standing in the kitchen — unless it's in the shared hallway.
Learn more on MDN