Script Valley
JavaScript: The Complete Language
JavaScript FoundationsLesson 1.2

var vs let vs const — which one to use and when

var hoisting, let block scope, const immutability, temporal dead zone, variable declaration best practices, re-assignment vs re-declaration

Three Ways to Declare Variables

JavaScript has three variable declaration keywords. Choosing correctly prevents entire categories of bugs.

var — Avoid in Modern Code

var is function-scoped and hoisted to the top of its enclosing function. This means you can reference it before the line it is declared — it just evaluates to undefined.

console.log(x); // undefined — NOT an error
var x = 5;
console.log(x); // 5

let — Default for Mutable Values

let is block-scoped. It exists only inside the nearest {} block and cannot be accessed before declaration (temporal dead zone).

let count = 0;
count = count + 1; // re-assignment is fine
// let count = 1;  // SyntaxError: re-declaration not allowed

const — Default for Everything Else

const prevents re-assignment. It does not make objects or arrays immutable — it only locks the binding.

const PI = 3.14159;
// PI = 3; // TypeError

const user = { name: "Ana" };
user.name = "Bob"; // fine — object properties can change
// user = {};       // TypeError — binding is locked

Rule of Thumb

Default to const. Use let when you know the value will change. Never use var in new code.

Up next

JavaScript data types explained with typeof

Sign in to track progress