Course contentsShow
← JavaScript
Lesson 68 of 2,7233. Variables and ScopeFree lesson

Declaring Variables with const

Use const to declare block-scoped variables that cannot be reassigned.

Declaring Variables with const

You'll learn how to declare variables that can't be reassigned, making your code safer and more predictable.

What is const?

The const keyword declares a constant variable — one that cannot be reassigned after its initial value is set. Like let, const creates block-scoped variables, but with an added layer of protection: you must initialize it immediately, and you can never point it to a different value.

Think of const like writing in permanent marker. Once you've written the value, you can't erase it and write something else. This is different from let, which is more like writing in pencil — you can erase and change it whenever you want.

Basic Syntax

const age = 30;
console.log(age); // 30

age = 31; // ❌ TypeError: Assignment to constant variable

You must assign a value when declaring:

const name; // ❌ SyntaxError: Missing initializer

Block Scope Still Applies

Like let, const is block-scoped:

const country = "USA";

if (true) {
  const country = "Canada"; // Different variable
  console.log(country); // "Canada"
}

console.log(country); // "USA"

When to Use const

Use const by default for any variable that won't be reassigned. This communicates intent to other developers (and your future self) that this value should remain unchanged throughout its scope.

Key Takeaway: const declares block-scoped variables that cannot be reassigned, providing protection against accidental changes and making your code's intent clearer. Always initialize const variables immediately.