Variables & Scope
How and where values are stored in memory. Master let, const, var, and the rules of block versus function scope.
What are variables and scope?
A variable is a named container for storing data in memory. In JavaScript, you declare a variable using let, const, or the legacy var keyword.
Scope is the set of rules that determines where a variable is accessible in your code. Think of it as a one-way mirror: inner code blocks can see out to outer variables, but outer code blocks cannot see in.
Why does it matter?
Choosing the right keyword prevents unexpected bugs. const guarantees the variable identifier will not be reassigned, making your code predictable.
Understanding scope is critical for keeping data private and avoiding collisions, where two parts of your program accidentally overwrite the same variable name.
How it works
const and let are block-scoped, meaning they only exist within the nearest curly braces {} (like an if statement or for loop).
var is function-scoped. If it is not inside a function, it leaks out and becomes a global variable, which is a common source of bugs.
When a variable is declared but not yet assigned, let and const sit in a Temporal Dead Zone (TDZ). Accessing them before initialization throws a ReferenceError. By contrast, var simply returns undefined.
Try it out
Declare variables inside and outside a block, then try to access them.
Scope Simulator
Declaration
Scenario
let x = "Hello";
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
constprevents reassignment, not mutation of objects.letandconstare block-scoped ({ }).varis function-scoped and hoists asundefined.- Accessing
let/constbefore declaration triggers the TDZ.
Done with this concept?
Mark it complete to track your progress. No login needed.