CPCODELAB
JavaScript

Variables: let, const, and var

9 min read

Declaring Variables

Variables are named containers for values. JavaScript has three keywords for declaring them: var (legacy), let (reassignable), and const (constant binding).

javascript
const siteName = "CPCODELAB";   // cannot be reassigned
let count = 0;               // can be reassigned
count = 1;                   // OK

// var — avoid in modern code
var old = "legacy";

const vs let

Use const by default. Switch to let only when you know you need to reassign the variable. const does not make objects immutable — it just prevents the variable from pointing at a different object.

javascript
const user = { name: "Alice" };
user.name = "Bob";  // allowed — modifying the object
// user = {};       // TypeError — reassignment not allowed

Why Avoid var?

var is function-scoped (not block-scoped), gets hoisted to the top of its function with an initial value of undefined, and can be redeclared in the same scope. All of these behaviours produce subtle bugs. let and const are block-scoped, are not initialized until their declaration is reached (Temporal Dead Zone), and cannot be redeclared.

Accessing a let or const variable before its declaration line throws a ReferenceError due to the Temporal Dead Zone (TDZ). This is intentional — it prevents a whole class of bugs that var hoisting used to hide.

Ready to test yourself?
Practice JavaScript— quiz & coding exercises