JAVASCRIPT
JavaScript const: Syntax, Usage, and Examples
const is a JavaScript keyword used to declare a variable that can’t be reassigned. It helps you write clearer code by showing which values should stay the same.
A constant variable is simply a variable you do not reassign, and const is the standard way to express that in modern JavaScript.
Learn JavaScript on Mimo
How to Use const
You use the const keyword when you want a variable name to always point to the same value.
Basic syntax
JSX
const appName ="Mimo";
console.log(appName);
Unlike let, a const variable must have a value right away. You can’t declare it first and assign later.
JSX
const user;// SyntaxError
user ="Mina";
This immediate assignment requirement is part of initialization, and it’s why people sometimes call the line a const declaration.
Block scope rules
const is block-scoped, just like let. That means the variable only exists inside the { ... } block where it’s created.
JSX
if (true) {
const status ="online";
console.log(status);// "online"
}
console.log(status);// ReferenceError
This is helpful because variables don’t leak into places where you don’t expect them.
Reassignment is not allowed
A const variable can’t point to a different value later.
JSX
const score =10;
score =15;// TypeError
Mutating objects and arrays is allowed
This part surprises many beginners: const prevents reassignment, but it does not freeze objects or arrays.
JSX
const colors = ["red","blue"];
colors.push("green");// allowed
console.log(colors);// ["red", "blue", "green"]
The variable colors still points to the same array in memory. You’re just changing what’s inside that array.
Same idea with objects:
JSX
const profile = {name:"Tariq",points:12 };
profile.points =13;// allowed
console.log(profile);// { name: "Tariq", points: 13 }
A const object can still have its properties updated, because the reference stays the same even when the contents change.
Declaring multiple constants
You can declare multiple constants in one statement, although it’s usually easier to read when each constant has its own line.
JSX
const firstName ="Lea", lastName ="Popović";
const inside loops
const works inside loops too, as long as you don’t reassign it.
JSX
const usernames = ["Ana","Sam","Noah"];
for (const nameof usernames) {
console.log(name);
}
The loop variable name is a new constant on each iteration.
When to Use const
const is a great default choice in modern JavaScript. It keeps your code stable and easier to reason about.
1) When a value should stay the same
Configuration values and fixed strings are classic examples.
JSX
constAPI_URL ="https://api.example.com";
constMAX_ITEMS =20;
2) When you want fewer accidental bugs
Reassigning the wrong variable happens more often than people admit. Using const makes JavaScript throw an error immediately instead of silently doing the wrong thing.
This is helpful for debugging, because a bad reassignment fails fast instead of quietly changing program state.
3) When you create helpers inside functions
Many variables exist just to support one operation and shouldn’t be changed afterward.
JSX
functionformatPrice(price) {
const taxRate =0.21;
return price + price * taxRate;
}
4) When working with objects and arrays you still plan to update
Even if you plan to push items into an array, you can still use const for the array variable itself.
JSX
const cart = [];
cart.push({name:"Notebook",price:4.99 });
The cart grows, but the cart variable stays locked to that same array.
Examples of const
Example 1: Saving user preferences
Imagine a settings page where you store a theme preference.
JSX
const defaultTheme ="dark";
functionloadTheme(userTheme) {
const theme = userTheme || defaultTheme;
console.log(`Theme loaded: ${theme}`);
}
loadTheme("light");
Here, defaultTheme should not change. The function can still pick a different value for theme depending on input.
In async code, you often keep stable references like configuration or DOM elements in const, even when the work happens later in time.
Example 2: Working with an array of items
A todo list is a good real-world example, because you keep adding things to the list.
JSX
const todos = [];
functionaddTodo(title) {
todos.push({ title,done:false });
}
addTodo("Study const");
addTodo("Write a mini project");
console.log(todos);
You’re mutating the array, but you’re not reassigning todos.
The done field is a boolean, and using a clear type like this makes the data shape easy to read.
Example 3: Updating an object property
A profile object might change over time, but the variable name stays attached to the same object.
JSX
const userProfile = {
name:"Maya",
level:1
};
functionlevelUp(profile) {
profile.level = profile.level +1;
}
levelUp(userProfile);
console.log(userProfile.level);// 2
This is common in apps that track progress, scores, or profile settings.
Example 4: Constants in DOM work
When you grab elements from the page, you usually don’t want to reassign those references.
JSX
const button =document.querySelector("#save-btn");
const messageBox =document.querySelector("#message");
button.addEventListener("click",() => {
messageBox.textContent ="Saved!";
});
The text changes, but the variables button and messageBox stay the same.
Event handlers like this are callbacks, and declaring your DOM references with const keeps them stable inside those callbacks.
Learn More About const
const vs let
People often say: “Use const by default, and switch to let when you must reassign.” That advice works surprisingly well.
- Use
constif the variable should keep the same reference. - Use
letif you need reassignment.
Here’s a simple comparison:
JSX
let steps =0;
steps = steps +1;// reassignment is expected
const username ="Nina";
// username = "Leo"; // not allowed
A loop counter often needs let:
JSX
for (let i =0; i <3; i++) {
console.log(i);
}
But iterating items can use const:
JSX
const items = ["tea","coffee","juice"];
for (const itemof items) {
console.log(item);
}
const vs var
var is the old-school variable keyword. You still see it in older tutorials and legacy code.
The main differences:
varis function-scoped,constis block-scoped.varallows re-declaration,constdoes not.varcan be used before its declaration (but givesundefined),constthrows an error.
A quick example of re-declaration confusion:
JSX
var points =5;
var points =10;// allowed
console.log(points);// 10
With const, that mistake gets blocked:
JSX
const points =5;
const points =10;// SyntaxError
Freezing objects for stricter immutability
If you truly want an object to be unchangeable, const isn’t enough. You can combine const with Object.freeze().
JSX
const settings =Object.freeze({
language:"en",
theme:"dark"
});
// settings.theme = "light"; // fails silently or throws in strict mode
Object.freeze() prevents changing existing properties, but it’s shallow. Nested objects can still be modified unless you freeze those too.
Common mistakes with const
1) Using const for values that need reassignment
This error usually shows up when building totals or counters.
JSX
const total =0;
total = total +5;// TypeError
Use let for values that change.
JSX
let total =0;
total = total +5;
2) Thinking const means “nothing can change”
Remember, object contents can still change.
JSX
const player = {name:"Luka",score:0 };
player.score =10;// allowed
3) Declaring const without assigning
JavaScript requires a value immediately.
JSX
const color;// SyntaxError
A let variable works better when you plan to assign later.
const naming conventions
Many teams write constants in uppercase when they represent fixed configuration.
JSX
constMAX_RETRIES =3;
Regular constants, like DOM references or one-time values inside functions, often use normal camelCase.
JSX
const saveButton =document.querySelector("#save");
You’ll also see patterns like const x in docs and examples as a minimal placeholder for “some constant value.”
If you come from languages like Python, PHP, or TypeScript, the idea of declaring a name that shouldn’t be reassigned will feel familiar, even though the syntax differs.
In modern ECMAScript, modules give you a cleaner top-level scope, so constants defined in a module don’t automatically become global.
When you build templates for HTML strings or UI snippets, you often store the template itself in a const and only swap in dynamic values where needed.
Summary
const creates variables that can’t be reassigned, which makes your code safer and easier to read. Use const for values that should stay stable, and remember that arrays and objects can still be mutated unless you freeze them.
Join 35M+ people learning for free on Mimo
4.8 out of 5 across 1M+ reviews
Check us out on Apple AppStore, Google Play Store, and Trustpilot