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
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.
1// Declare a constant for the maximum number of attempts2const MAX_ATTEMPTS = 3;34// Declare a constant for a fixed API endpoint URL5const API_URL = 'https://api.example.com/data';67// Print the values to see them8console.log('Max Attempts:', MAX_ATTEMPTS); // Output: Max Attempts: 39console.log('API URL:', API_URL); // Output: API URL: https://api.example.com/data1011// Try to change MAX_ATTEMPTS (this will cause an error)12// MAX_ATTEMPTS = 5; // ❌ TypeError: Assignment to constant variable.1314// 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.
1// Constant declared outside a block (global scope for this script)2const GLOBAL_MESSAGE = 'Hello from global!';34if (true) {5 // Constant declared inside this 'if' block6 const BLOCK_NUMBER = 10;7 console.log(GLOBAL_MESSAGE); // Works: GLOBAL_MESSAGE is available here8 console.log(BLOCK_NUMBER); // Works: BLOCK_NUMBER is available inside its block910 // Declaring a constant object11 const user = { name: 'Alice', age: 30 };12 console.log(user); // { name: 'Alice', age: 30 }1314 // You CAN change properties of a const object15 user.age = 31;16 console.log(user); // { name: 'Alice', age: 31 }1718 // You CANNOT reassign the const object itself19 // user = { name: 'Bob', age: 25 }; // ❌ TypeError: Assignment to constant variable.20}2122// console.log(BLOCK_NUMBER); // ❌ ReferenceError: BLOCK_NUMBER is not defined23 // This is because BLOCK_NUMBER is block-scoped.
const APP_NAME = 'My App';APP_NAME = 'New App'; // ❌ Error: Cannot reassignconsole.log(APP_NAME);
const settings = { theme: 'dark' };settings.theme = 'light'; // ✅ Works: Changing property, not reassignmentconsole.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.
// API base URL that never changesconst BASE_URL = 'https://api.mysite.com';// Maximum items allowed in a listconst MAX_ITEMS = 100;// Mathematical constantconst PI = 3.14159;// User object (reference is constant, properties can change)const userProfile = { id: 1, name: 'Ava' };
// A counter that increaseslet count = 0;count = count + 1;// User's current scorelet currentScore = 10;currentScore = currentScore + 5;// A message that might be updatedlet statusMessage = 'Loading...';statusMessage = 'Finished!';
// API base URL that never changesconst BASE_URL = 'https://api.mysite.com';// Maximum items allowed in a listconst MAX_ITEMS = 100;// Mathematical constantconst PI = 3.14159;// User object (reference is constant, properties can change)const userProfile = { id: 1, name: 'Ava' };
// A counter that increaseslet count = 0;count = count + 1;// User's current scorelet currentScore = 10;currentScore = currentScore + 5;// A message that might be updatedlet 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.
Define application constants
Start by setting up important, unchanging values for your application. This might include API keys, default settings, or fixed messages.
1const API_KEY = 'your_super_secret_key';2const DEFAULT_THEME = 'dark';3const GREETING_MESSAGE = 'Welcome to our app!';
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.
1const DISCOUNT_RATE = 0.10; // 10% discount2let productPrice = 250;3let finalPrice = productPrice * (1 - DISCOUNT_RATE);4console.log('Final Price:', finalPrice); // 225
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.
1// Assume a button with id='myButton' exists in HTML2const myButton = document.getElementById('myButton');3const appTitle = document.querySelector('.app-title');45// You can still interact with the element, e.g., change its text6if (myButton) {7 myButton.textContent = 'Click Me!';8}910// You cannot reassign myButton to a different element11// 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
| Feature | Description | Example |
|---|---|---|
| Reassignment | Cannot be reassigned after initial declaration. | `const x = 10; x = 20;` ❌ |
| Scope | Block-scoped: only available within the `{}` block where it's declared. | `if(true){ const y = 5; } console.log(y);` ❌ |
| Initialization | Must be initialized with a value at the time of declaration. | `const z;` ❌ |
| Object/Array | The binding is constant, but properties/elements can be mutated. | `const obj = {}; obj.prop = 1;` ✅ |
Test Your Knowledge
Test Your Knowledge
Which statement about const is true?
What will happen if you run this code? const PI = 3.14; PI = 3.14159;
Consider this code: if (true) { const message = 'Hello'; } console.log(message); What is the result?
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
- 1const — declares a variable whose value cannot be reassigned after initialization.
- 2Block Scope —
constvariables are only accessible within the{}block where they are defined. - 3Initialization — you must assign a value to a
constvariable immediately upon declaration. - 4No Reassignment — trying to assign a new value to a
constvariable will cause aTypeError. - 5Object/Array Mutation —
constprevents reassignment of the variable, but you can still change the properties of aconstobject or elements of aconstarray. - 6Prefer const — use
constfor values that should not change; switch toletonly if reassignment is truly needed. - 7Readability — using
constmakes 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
construles are broken, which aids debugging. - 10Modern JavaScript —
const(along withlet) is the standard way to declare variables in modern JavaScript, replacingvar.
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.