Variables & Scope

How and where values are stored in memory. Master let, const, var, and the rules of block versus function scope.

JavaScript6 min readConcept 2 of 62

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

function testScope() {
{
// Inside a block
let x = "Hello";
console.log(x);
}
}
testScope();
Console Output
> "Hello"
ilet is block-scoped, so it safely remains trapped inside the curly braces.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What happens if you try to access a `let` variable before its declaration?
  2. 2Which of the following keywords is block-scoped?
  3. 3Can you mutate an object declared with `const`?

Remember this

  • const prevents reassignment, not mutation of objects.
  • let and const are block-scoped ({ }).
  • var is function-scoped and hoists as undefined.
  • Accessing let/const before declaration triggers the TDZ.

Done with this concept?

Mark it complete to track your progress. No login needed.