javascript

const - Block Scoped Constants

Learn what JavaScript's 'const' keyword means for block-scoped constants. Understand how to declare fixed values, prevent reassignment, and handle objects.

11 min read 8 sections Tutorial
Share

The `const` keyword in JavaScript lets you create variables whose values cannot be changed after they are first set. These are called constants. Using `const` makes your code safer and easier to understand because you know a value will always stay the same.

const - Block Scoped Constants

const - Block Scoped Constants

In JavaScript, const is a special keyword. You use it to declare a constant variable. This means the variable's value cannot be changed or re-assigned once it is set.

const also creates block-scoped variables. This means the variable only exists inside the code block where it was created. This helps keep your code organized and prevents unexpected changes.

What is 'const'?

const declares a constant variable. Its value cannot be reassigned after initialization. It is also block-scoped, meaning it is only available within the curly braces {} where it was defined.

Fixed Value

Once you set a const variable's value, you cannot change it to something else.

Block Scope

A const variable only works inside the specific code block where you declared it.

Prevents Bugs

Using const stops you from accidentally changing important values in your program.

Must Initialize

You must give a const variable a value immediately when you declare it.

Declaring a 'const' Variable

Getting Started

Declaring a 'const' Variable

To declare a constant, you use the const keyword, followed by the variable name, an equals sign =, and then the value. You must give it a value right away.

If you try to change a const variable's value later, JavaScript will stop your program and show an error. This is a good thing, because it tells you that you are trying to do something you said you would not do.

javascript
1// Declare a constant for the maximum number of attempts
2const MAX_ATTEMPTS = 3;
3
4// Declare a constant for a fixed API endpoint URL
5const API_URL = 'https://api.example.com/data';
6
7// Print the values to see them
8console.log('Max Attempts:', MAX_ATTEMPTS); // Output: Max Attempts: 3
9console.log('API URL:', API_URL); // Output: API URL: https://api.example.com/data
10
11// Try to change MAX_ATTEMPTS (this will cause an error)
12// MAX_ATTEMPTS = 5; // ❌ TypeError: Assignment to constant variable.
13
14// Try to change API_URL (this will also cause an error)
15// API_URL = 'https://api.newapi.com'; // ❌ TypeError: Assignment to constant variable.

Always initialize 'const' variables

You must give a const variable a value as soon as you declare it. If you do not, JavaScript will throw a SyntaxError.

const GAME_TITLE; // ❌ SyntaxError: Missing initializer in const declaration
GAME_TITLE = 'My Game';

This is different from let, which allows you to declare a variable without an initial value.

Block Scope and Constant Binding

Block Scope and Constant Binding

When we say const is block-scoped, it means the variable only lives inside the nearest pair of curly braces {}. If you declare a const inside an if statement or a for loop, it cannot be used outside of that block.

Also, const makes a constant binding. This means the variable name always points to the same value. For simple values like numbers or text, this means the value itself cannot change. For complex values like objects or arrays, it means the variable name will always point to the same object or array in memory. However, the contents of that object or array can still be changed.

javascript
1// Constant declared outside a block (global scope for this script)
2const GLOBAL_MESSAGE = 'Hello from global!';
3
4if (true) {
5 // Constant declared inside this 'if' block
6 const BLOCK_NUMBER = 10;
7 console.log(GLOBAL_MESSAGE); // Works: GLOBAL_MESSAGE is available here
8 console.log(BLOCK_NUMBER); // Works: BLOCK_NUMBER is available inside its block
9
10 // Declaring a constant object
11 const user = { name: 'Alice', age: 30 };
12 console.log(user); // { name: 'Alice', age: 30 }
13
14 // You CAN change properties of a const object
15 user.age = 31;
16 console.log(user); // { name: 'Alice', age: 31 }
17
18 // You CANNOT reassign the const object itself
19 // user = { name: 'Bob', age: 25 }; // ❌ TypeError: Assignment to constant variable.
20}
21
22// console.log(BLOCK_NUMBER); // ❌ ReferenceError: BLOCK_NUMBER is not defined
23 // This is because BLOCK_NUMBER is block-scoped.
✗ BadWrong — Reassigning const
const APP_NAME = 'My App';
APP_NAME = 'New App'; // ❌ Error: Cannot reassign
console.log(APP_NAME);
✓ GoodCorrect — Changing const object property
const settings = { theme: 'dark' };
settings.theme = 'light'; // ✅ Works: Changing property, not reassignment
console.log(settings.theme); // light

When to Use 'const' vs. 'let'

When to Use 'const' vs. 'let'

Deciding between const and let is important. You should use const for any value that you know will not change during your program's execution. This includes things like configuration settings, fixed numbers like Pi, or URLs.

Use let when you expect a variable's value to change. This is common for counters, user input that updates, or results of calculations that might be modified later. A good rule of thumb is to start with const and only switch to let if you find you need to reassign the variable.

Use const for fixed values
// API base URL that never changes
const BASE_URL = 'https://api.mysite.com';
// Maximum items allowed in a list
const MAX_ITEMS = 100;
// Mathematical constant
const PI = 3.14159;
// User object (reference is constant, properties can change)
const userProfile = { id: 1, name: 'Ava' };
VS
Use let for changing values
// A counter that increases
let count = 0;
count = count + 1;
// User's current score
let currentScore = 10;
currentScore = currentScore + 5;
// A message that might be updated
let statusMessage = 'Loading...';
statusMessage = 'Finished!';

Prefer 'const' by default

A widely accepted best practice in modern JavaScript is to use const whenever possible. If you later realize you need to change the variable's value, you can easily switch it to let. This approach helps you write more predictable and bug-free code.

Practical Uses for 'const'

Practical Uses for 'const'

const is very useful for defining values that act as settings or important configuration. This makes your code more readable because anyone looking at it immediately knows these values are not meant to change. It also prevents errors from accidental modifications.

1

Define application constants

Start by setting up important, unchanging values for your application. This might include API keys, default settings, or fixed messages.

javascript
1const API_KEY = 'your_super_secret_key';
2const DEFAULT_THEME = 'dark';
3const GREETING_MESSAGE = 'Welcome to our app!';
2

Use constants in calculations

You can use const variables in calculations just like any other variable. The result of the calculation can be stored in a let variable if it needs to change.

javascript
1const DISCOUNT_RATE = 0.10; // 10% discount
2let productPrice = 250;
3let finalPrice = productPrice * (1 - DISCOUNT_RATE);
4console.log('Final Price:', finalPrice); // 225
3

Store DOM elements

When you get an HTML element from the page, its reference usually does not change. So, const is perfect for storing these elements.

JS · Browser
1// Assume a button with id='myButton' exists in HTML
2const myButton = document.getElementById('myButton');
3const appTitle = document.querySelector('.app-title');
4
5// You can still interact with the element, e.g., change its text
6if (myButton) {
7 myButton.textContent = 'Click Me!';
8}
9
10// You cannot reassign myButton to a different element
11// myButton = document.getElementById('anotherButton'); // ❌ TypeError

Do not confuse 'const' with deep immutability

Remember that const only prevents the reassignment of the variable itself. If you declare an object or array with const, you can still change its internal properties or elements.

const COLORS = ['red', 'green'];
COLORS.push('blue'); // ✅ This works! Array contents changed.
console.log(COLORS); // ['red', 'green', 'blue']

// COLORS = ['yellow']; // ❌ This would be a TypeError (reassignment)

const does not make the contents of objects or arrays immutable.

const Keyword Reference

const Keyword Reference

FeatureDescriptionExample
ReassignmentCannot be reassigned after initial declaration.`const x = 10; x = 20;` ❌
ScopeBlock-scoped: only available within the `{}` block where it's declared.`if(true){ const y = 5; } console.log(y);` ❌
InitializationMust be initialized with a value at the time of declaration.`const z;` ❌
Object/ArrayThe binding is constant, but properties/elements can be mutated.`const obj = {}; obj.prop = 1;` ✅

Test Your Knowledge

Test Your Knowledge

Test Your Knowledge

Quick Check

Which statement about const is true?

Quick Check

What will happen if you run this code? const PI = 3.14; PI = 3.14159;

Quick Check

Consider this code: if (true) { const message = 'Hello'; } console.log(message); What is the result?

Quick Check

If you declare an array with const, like const myArray = [1, 2];, can you add a new element to it? (e.g., myArray.push(3);)

Quick Reference

Quick Reference

Quick Reference

Pro Tips
  • 1const — declares a variable whose value cannot be reassigned after initialization.
  • 2Block Scopeconst variables are only accessible within the {} block where they are defined.
  • 3Initialization — you must assign a value to a const variable immediately upon declaration.
  • 4No Reassignment — trying to assign a new value to a const variable will cause a TypeError.
  • 5Object/Array Mutationconst prevents reassignment of the variable, but you can still change the properties of a const object or elements of a const array.
  • 6Prefer const — use const for values that should not change; switch to let only if reassignment is truly needed.
  • 7Readability — using const makes your code easier to understand by signaling fixed values.
  • 8Prevents Bugs — it helps catch accidental changes to critical data early.
  • 9Error Handling — JavaScript throws clear errors when const rules are broken, which aids debugging.
  • 10Modern JavaScriptconst (along with let) is the standard way to declare variables in modern JavaScript, replacing var.

Variable Scope

Deepen your understanding of block, function, and global scope in JavaScript.

let Keyword

Learn about let for variables that can be reassigned and its block-scoping behavior.

var Keyword

Explore the older var keyword, its function scope, and why it's generally avoided now.

Data Types

Understand the different types of values (numbers, strings, objects) that const can hold.

You've Mastered 'const'!

You now understand how to use const to declare block-scoped constants, prevent reassignment, and handle complex data types like objects and arrays. This knowledge is crucial for writing robust and predictable JavaScript code.

Try it in the Javascript Compiler

Run and experiment with Javascript code right in your browser — no setup needed.

Continue Learning