Script Valley
JavaScript Tutorial for Beginners to Advanced
JavaScript Basics: Variables, Data Types, and OperatorsLesson 2.1

JavaScript Variables: var, let, and const

var, let, const, hoisting, block scope, temporal dead zone, when to use each

JavaScript Variables: var, let, and const

Variables are named containers for storing data in JavaScript. Understanding how to declare variables correctly is one of the most important fundamentals in this JavaScript tutorial, because the wrong choice leads to bugs that are very difficult to trace.

The var Keyword

The var keyword was the original way to declare variables in JavaScript. It is function-scoped, meaning it is accessible anywhere within the function it was declared in, regardless of blocks like if-statements or loops. It is also hoisted, which means the declaration is moved to the top of its scope and initialized as undefined before any code runs.

var city = 'London';
console.log(city); // 'London'

if (true) {
  var country = 'UK'; // still accessible outside the block
}
console.log(country); // 'UK' — this can cause unexpected behaviour

These behaviours make var unpredictable. It is considered legacy and should be avoided in modern JavaScript code.

The let Keyword

The let keyword was introduced in ES6. It is block-scoped, meaning it only exists within the curly braces where it was declared. It cannot be re-declared in the same scope, though its value can be changed.

let score = 0;
score = 10; // re-assignment is fine

if (true) {
  let localVar = 'only here';
  console.log(localVar); // works
}
// console.log(localVar); // ReferenceError — not accessible here

The const Keyword

The const keyword declares a variable whose binding cannot be reassigned. It is also block-scoped. Use const by default for everything that should not change. Note that for objects and arrays declared with const, the contents can still be modified — only the reference is locked.

const PI = 3.14159;
// PI = 3; // TypeError — cannot reassign a const

const user = { name: 'Alice', age: 30 };
user.age = 31; // This works — we are modifying the object, not the reference
console.log(user.age); // 31

When to Use Each

Follow this simple rule: use const by default. If you know a variable's value will change (like a counter in a loop), use let. Never use var in modern code. This rule is followed by professional JavaScript developers worldwide and is enforced by most linters.

Up next

JavaScript Data Types

Sign in to track progress