JavaScript
/Beginner
Scope
Definition
Scope determines the accessibility (visibility) of variables, objects, and functions from different parts of the code. JavaScript has Global scope, Function scope, and Block scope.
Explain Like I'm New
Think of scope like rooms in a house with one-way glass doors. If you are in a small inner room (block/function scope), you can see out into the living room (global scope) and use things there. But someone in the living room cannot look into your small inner room and use your things.
Real World Example
If you define a variable `password` inside a `login()` function, the rest of the application (outside the function) has no idea that the `password` variable exists. It's safe inside its room.
Common Use Cases
- •Preventing variable naming collisions
- •Keeping internal states private
- •Managing memory efficiently by discarding variables when the scope ends
Interactive Example
Loading...
Console output will appear here...
Interview Questions
basic
- What is Global Scope?
- What is the difference between Function Scope and Block Scope?
intermediate
- What is Lexical Scope?
- How do var, let, and const behave differently with respect to scope?
advanced
- What is the Scope Chain?
- How does scope relate to closures?
trick
- Can a variable declared with var inside an if-statement be accessed outside of it?