- Array() find
- -- operator
- -= operator
- ++ operator
- += operator
- Accessing and setting content
- AND operator
- Array concat() method
- Array indexOf()
- Array length
- Array pop()
- Array shift
- Array slice() method
- Arrays
- Arrow function
- Async await
- Booleans
- Braces
- Callback function
- Calling the function
- Class
- Closure
- Code block
- Comment
- Conditions
- Console
- const
- Constructor
- Creating a p element
- Data types
- Date getTime()
- Destructuring
- DOM
- Else
- Else if
- Enum
- Environment
- Equals operator
- Error Handling
- ES6
- Event listener method
- Event loop
- Events
- Export statement
- Extends
- Fetch API
- Filter
- For loop
- forEach()
- Function
- Function bind()
- Function name
- Greater than
- Head element
- Hoisting
- If statement
- Import statement
- includes()
- Infinity property
- isNaN function
- Iterator
- JSON
- Less than
- Let
- Local storage
- Map
- Methods
- Module
- Modulo operator
- Node.js
- null
- Numbers
- Object
- Object.keys()
- Optional chaining
- Overriding methods
- Parameters
- Promises
- Prototype
- Random
- Reduce
- Regex
- Regular expressions
- Removing an element
- Replace
- Scope
- Session storage
- setInterval
- setTimeout() method
- Sleep() function
- Sort
- Splice
- Spread operator
- String
- String concat()
- String indexOf()
- String slice() method
- Substring
- Switch statement
- Template literals
- Ternary operator
- throw Statement
- Title
- Try catch
- Type conversion
- undefined
- var
- void Operator
- What is JavaScript?
- While loop
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.
How to Use const
You use const when you want a variable name to always point to the same value.
Learn JavaScript on Mimo
Basic syntax
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.
const user;// SyntaxError
user ="Mina";
Block scope rules
const is block-scoped, just like let. That means the variable only exists inside the { ... } block where it’s created.
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.
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.
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:
const profile = {name:"Tariq",points:12 };
profile.points =13;// allowed
console.log(profile);// { name: "Tariq", points: 13 }
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.
const firstName ="Lea", lastName ="Popović";
const inside loops
const works inside loops too, as long as you don’t reassign it.
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.
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.
3) When you create helpers inside functions
Many variables exist just to support one operation and shouldn’t be changed afterward.
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.
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.
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.
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.
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.
Example 3: Updating an object property
A profile object might change over time, but the variable name stays attached to the same object.
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.
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.
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:
let steps =0;
steps = steps +1;// reassignment is expected
const username ="Nina";
// username = "Leo"; // not allowed
A loop counter often needs let:
for (let i =0; i <3; i++) {
console.log(i);
}
But iterating items can use const:
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:
var points =5;
var points =10;// allowed
console.log(points);// 10
With const, that mistake gets blocked:
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().
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.
const total =0;
total = total +5;// TypeError
Use let for values that change.
let total =0;
total = total +5;
2) Thinking const means “nothing can change”
Remember, object contents can still change.
const player = {name:"Luka",score:0 };
player.score =10;// allowed
3) Declaring const without assigning
JavaScript requires a value immediately.
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.
constMAX_RETRIES =3;
Regular constants, like DOM references or one-time values inside functions, often use normal camelCase.
const saveButton =document.querySelector("#save");
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. When reassignment is part of the job, switch to let and keep moving.
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