JavaScript const
JavaScript provides several ways to create variables, and const is one of the most commonly used declarations in modern JavaScript. The const keyword is used when you want to create a variable whose binding cannot be reassigned after it has been initialized.
The name const comes from constant. However, it is important to understand that const does not make every value completely immutable. For primitive values, the value cannot be changed through reassignment. For objects and arrays, their contents can still be modified even though the variable itself cannot be assigned to a different object or array.
The const declaration was introduced with ECMAScript 2015 (ES6). It provides safer and clearer variable handling than using var in many situations.
What Is const in JavaScript?
const is a JavaScript keyword used to declare a variable that must be initialized when it is created and cannot later be reassigned.
The basic syntax is:
const variableName = value;
For example:
const age = 25;
console.log(age);
Output:
25
Trying to assign another value to age causes an error:
const age = 25;
age = 30;
This results in a TypeError because a variable declared with const cannot be reassigned.
Why Was const Introduced?
Older JavaScript code often used var for variable declarations. However, var has function scope and allows redeclaration, which can sometimes lead to unexpected behavior.
ES6 introduced let and const to provide more predictable block-scoped variable declarations.
For example:
const website = "NewNid";
This clearly communicates that the variable should not be reassigned.
Using const whenever reassignment is not required makes code easier to understand and reduces accidental changes.
Basic Example of const
Here is a simple example:
const name = "Rahul";
const age = 28;
console.log(name);
console.log(age);
Output:
Rahul
28
Both variables are declared using const.
They can be read and used normally, but their bindings cannot be reassigned.
const Must Be Initialized
One of the most important rules of const is that it must be assigned a value at the time of declaration.
This is valid:
const country = "India";
This is invalid:
const country;
JavaScript throws a SyntaxError because a const declaration requires an initializer.
Unlike let, you cannot declare a const variable first and assign its value later.
For example:
let city;
city = "Bhubaneswar";
This is valid.
But:
const city;
city = "Bhubaneswar";
is not valid.
Reassigning a const Variable
A const variable cannot be reassigned.
Example:
const price = 100;
price = 200;
This produces a TypeError.
The original binding remains associated with the original value.
Another example:
const language = "JavaScript";
language = "Python";
This is not allowed.
If you need to change the variable’s value later, use let instead:
let language = "JavaScript";
language = "Python";
console.log(language);
Output:
Python
const Does Not Mean the Value Is Always Immutable
This is one of the most misunderstood features of JavaScript.
Consider:
const person = {
name: "Amit",
age: 25
};
You cannot replace the entire object:
person = {
name: "Rahul",
age: 30
};
But you can change a property inside the object:
person.age = 30;
console.log(person.age);
Output:
30
Why?
Because const prevents reassignment of the variable binding. It does not automatically freeze the object referenced by that variable.
const With Objects
Objects declared using const can have their properties changed.
Example:
const student = {
name: "Ravi",
course: "JavaScript"
};
student.name = "Aman";
console.log(student.name);
Output:
Aman
The object itself has not been replaced. A property inside the object was changed.
You can also add properties:
const user = {
name: "Priya"
};
user.age = 24;
console.log(user);
The resulting object contains both name and age.
Can a const Object Be Replaced?
No.
For example:
const user = {
name: "Priya"
};
user = {
name: "Neha"
};
This attempts to assign a completely new object to user, so JavaScript throws a TypeError.
The following, however, is allowed:
user.name = "Neha";
The distinction is important:
- Reassigning the variable: not allowed
- Changing an object’s properties: allowed
- Adding object properties: allowed
- Removing object properties: allowed
const With Arrays
The same rule applies to arrays.
You can declare an array using const:
const fruits = ["Apple", "Banana", "Mango"];
You cannot assign a new array:
fruits = ["Orange", "Grapes"];
But you can modify the existing array:
fruits.push("Orange");
console.log(fruits);
Output:
["Apple", "Banana", "Mango", "Orange"]
You can also change an existing element:
fruits[0] = "Grapes";
This is allowed because the array object itself has not been replaced.
Adding and Removing Array Elements
A const array can be modified with methods such as:
const numbers = [10, 20, 30];
numbers.push(40);
numbers.pop();
console.log(numbers);
The array variable remains associated with the same array object.
The following is not allowed:
numbers = [50, 60, 70];
This attempts to reassign the variable.
const and Primitive Values
Primitive values behave differently because they do not have mutable properties in the same way objects do.
JavaScript primitive types include:
- String
- Number
- BigInt
- Boolean
- Undefined
- Symbol
- Null
For example:
const score = 100;
You cannot do:
score = 200;
Similarly:
const name = "Dibya";
name = "Amit";
is not allowed.
const and Strings
Strings are primitive values.
Example:
const message = "Hello";
You cannot assign another string:
message = "Hi";
However, JavaScript strings are immutable, so individual characters cannot be changed directly either.
const word = "Hello";
An operation such as:
word[0] = "Y";
does not modify the string into "Yello".
If you need a different string, you create a new value and use a different variable or a let binding.
const and Numbers
Numbers are also primitive values.
const age = 25;
This is valid:
console.log(age + 5);
Output:
30
But this is not:
age = age + 5;
Because it attempts to reassign the const variable.
const and Boolean Values
Boolean values are either true or false.
Example:
const isLoggedIn = true;
console.log(isLoggedIn);
You cannot later write:
isLoggedIn = false;
If the state is expected to change, use let.
const Has Block Scope
One of the major advantages of const is that it is block-scoped.
A block is generally code enclosed within curly braces {}.
For example:
{
const message = "Hello";
console.log(message);
}
The variable exists only inside that block.
Trying to access it outside the block:
{
const message = "Hello";
}
console.log(message);
results in a ReferenceError.
const Inside an if Block
Consider this example:
if (true) {
const message = "Welcome";
console.log(message);
}
The variable is available inside the if block.
It is not available outside:
if (true) {
const message = "Welcome";
}
console.log(message);
This produces an error because message is outside its scope.
const Inside Loops
const can be used inside loops, depending on the type of loop.
For example:
for (const fruit of ["Apple", "Banana", "Mango"]) {
console.log(fruit);
}
This works because each iteration gets its own loop binding.
You can also use const with for...in:
const person = {
name: "Amit",
age: 25
};
for (const key in person) {
console.log(key);
}
However, a traditional for loop normally needs let if the counter changes:
for (let i = 0; i < 5; i++) {
console.log(i);
}
Using const for i would fail because the loop attempts to update the counter.
const in Functions
A const variable can be declared inside a function.
function greet() {
const message = "Hello, world!";
console.log(message);
}
greet();
The variable is available within the function’s relevant block scope.
It cannot normally be accessed outside that scope.
const and Nested Blocks
JavaScript allows nested blocks.
const outer = "Outer";
{
const inner = "Inner";
console.log(outer);
console.log(inner);
}
The inner block can access outer because the outer variable is in an enclosing scope.
But the outer scope cannot access inner.
{
const inner = "Inner";
}
console.log(inner);
This results in a ReferenceError.
Temporal Dead Zone and const
const declarations are affected by the Temporal Dead Zone (TDZ).
The TDZ is the period between entering a scope and reaching the declaration of a let or const variable.
For example:
console.log(value);
const value = 10;
This causes a ReferenceError.
The declaration exists in the scope, but the variable cannot be accessed before its declaration is evaluated.
The same general TDZ behavior applies to let.
const Is Not Hoisted Like var
It is common to say that const is “not hoisted,” but that statement is an oversimplification.
const declarations are processed during scope creation, but they remain inaccessible until execution reaches their declaration. This inaccessible period is the Temporal Dead Zone.
Compare this with var:
console.log(x);
var x = 10;
Output:
undefined
With const:
console.log(x);
const x = 10;
A ReferenceError occurs.
This difference is one reason const and let are safer than many older var patterns.
Cannot Redeclare a const Variable in the Same Scope
A const variable cannot be declared twice in the same scope.
For example:
const name = "Amit";
const name = "Rahul";
This produces a SyntaxError.
The same restriction applies to let in the same scope.
However, nested scopes can contain another variable with the same name:
const name = "Amit";
{
const name = "Rahul";
console.log(name);
}
console.log(name);
Output:
Rahul
Amit
The inner declaration shadows the outer declaration.
const With Destructuring
const works very well with destructuring.
For arrays:
const colors = ["Red", "Green", "Blue"];
const [first, second, third] = colors;
console.log(first);
console.log(second);
console.log(third);
Output:
Red
Green
Blue
For objects:
const user = {
name: "Rahul",
age: 30
};
const { name, age } = user;
console.log(name);
console.log(age);
Destructuring is particularly useful when working with objects returned by functions or APIs.
const With Default Values in Destructuring
You can also use default values:
const user = {
name: "Amit"
};
const { name, age = 18 } = user;
console.log(name);
console.log(age);
Output:
Amit
18
The default value is used because age is not present in the object.
const With Functions
Function expressions are often stored in const variables.
Example:
const greet = function () {
console.log("Hello!");
};
greet();
You can also store arrow functions:
const add = (a, b) => {
return a + b;
};
console.log(add(10, 20));
Output:
30
Using const here prevents reassignment of the function binding.
Can a const Function Be Changed?
The function binding cannot be reassigned.
const greet = () => {
console.log("Hello");
};
greet = () => {
console.log("Hi");
};
This causes a TypeError.
However, this does not mean that every object or state associated with a function is immutable. It simply means the greet binding cannot be assigned to another function.
const and Class Declarations
Classes can also be assigned to a const variable:
const Person = class {
constructor(name) {
this.name = name;
}
};
const person = new Person("Amit");
console.log(person.name);
The Person binding cannot be reassigned.
const and Modules
In JavaScript modules, const is frequently used for values that should not be reassigned.
For example:
const API_URL = "https://example.com/api";
A module may export it:
export const API_URL = "https://example.com/api";
Another module can import it:
import { API_URL } from "./config.js";
The imported binding cannot simply be reassigned by the importing module.
const and Global Variables
A top-level const declaration behaves differently from a var declaration in a classic browser script.
For example:
const siteName = "NewNid";
It does not create a property named siteName on the global window object in the way a top-level var declaration does.
This is another important difference between modern variable declarations and older var behavior.
const in Strict Mode
const works naturally with strict mode.
For example:
"use strict";
const value = 10;
console.log(value);
Strict mode does not change the fundamental rule that a const binding cannot be reassigned.
const and Object.freeze()
If you need an object whose properties should also be protected from modification, const alone is not enough.
You can use Object.freeze():
const user = Object.freeze({
name: "Amit",
age: 25
});
Now attempts to change the object’s properties are prevented according to the semantics of Object.freeze().
However, Object.freeze() is shallow.
For example:
const user = Object.freeze({
name: "Amit",
address: {
city: "Bhubaneswar"
}
});
The top-level object is frozen, but the nested address object is not automatically deeply frozen.
Therefore:
user.address.city = "Cuttack";
can still modify the nested object.
const vs let
The two modern variable declarations are similar because both are block-scoped.
The key difference is reassignment.
const country = "India";
cannot be reassigned.
let country = "India";
country = "Japan";
can be reassigned.
A simple rule is:
Use const when the binding should not be reassigned. Use let when reassignment is required.
const vs var
const and var have several important differences.
| Feature | const | let | var |
|---|---|---|---|
| Block scoped | Yes | Yes | No |
| Function scoped | Yes, within function blocks | Yes, within function blocks | Yes |
| Must initialize | Yes | No | No |
| Reassignment | No | Yes | Yes |
| Same-scope redeclaration | No | No | Yes |
| Temporal Dead Zone | Yes | Yes | No |
| Introduced | ES6 | ES6 | Older JavaScript |
For modern JavaScript development, const and let are generally preferred over var.
When Should You Use const?
Use const when you do not need to reassign the variable.
For example:
const firstName = "Amit";
const birthYear = 1998;
const country = "India";
These values are not expected to be reassigned.
Other common examples include:
const API_URL = "https://example.com";
const MAX_USERS = 100;
const taxRate = 0.18;
const button = document.querySelector("#submit");
Using const communicates your intention clearly.
When Should You Use let Instead?
Use let when a variable needs to receive a different value later.
For example:
let score = 0;
score = 10;
score = 20;
A counter is another common example:
let count = 0;
count++;
console.log(count);
Using const in this situation would cause an error because the variable is reassigned.
Should You Always Use const?
A common modern JavaScript recommendation is:
Prefer const by default, and use let when reassignment is necessary.
This is not because const makes all data immutable. Instead, it makes the variable binding more predictable.
For example:
const user = getUser();
If you later see:
user = getAnotherUser();
you immediately know the code is not allowed.
That restriction can help prevent accidental reassignment.
Common Mistake: Thinking const Makes Objects Immutable
This is probably the most common misunderstanding.
Incorrect assumption:
const person = {
name: "Amit"
};
person.name = "Rahul";
Some beginners expect this to produce an error.
It does not.
The property can be changed because the object itself has not been reassigned.
To understand it simply:
const variable → cannot point to a different object
object contents → may still be mutable
Common Mistake: Declaring const Without a Value
This is invalid:
const total;
Instead, initialize it immediately:
const total = 0;
If you genuinely need to assign the value later, use:
let total;
Common Mistake: Using const for a Changing Counter
This is incorrect:
const count = 0;
count++;
The ++ operator attempts to assign a new value to count.
Use:
let count = 0;
count++;
Common Mistake: Confusing const With Constant Object Properties
Consider:
const settings = {
theme: "light"
};
The variable settings cannot be reassigned, but settings.theme can normally be changed.
If you need stronger immutability, use an appropriate immutable-data technique such as Object.freeze() or immutable update patterns.
Common Mistake: Accessing const Before Declaration
This code is invalid:
console.log(name);
const name = "Amit";
The error occurs because name is in the Temporal Dead Zone before its declaration is evaluated.
The correct approach is:
const name = "Amit";
console.log(name);
Best Practices for Using const
Prefer const for Non-Reassigned Bindings
Instead of:
var website = "NewNid";
modern JavaScript commonly uses:
const website = "NewNid";
when reassignment is unnecessary.
Use Descriptive Names
Prefer:
const customerName = "Rahul";
over:
const x = "Rahul";
Meaningful names make code easier to maintain.
Initialize const Immediately
Always provide a value:
const country = "India";
Do Not Use const When Reassignment Is Required
If a value needs to change:
let temperature = 25;
temperature = 30;
Use let.
Avoid Unnecessary Mutation
Even though const allows object and array mutation, excessive mutation can make larger programs harder to understand.
For example, instead of repeatedly changing shared objects, consider creating new objects when appropriate:
const user = {
name: "Amit",
age: 25
};
const updatedUser = {
...user,
age: 26
};
Here, the original object remains unchanged.
Naming Conventions for const
JavaScript does not require a special naming style for const, but common conventions improve readability.
For normal variables, camelCase is common:
const firstName = "Amit";
const totalPrice = 500;
const userAccount = {};
For values treated as application-wide constants, uppercase names with underscores are often used:
const MAX_USERS = 100;
const API_URL = "https://example.com";
const DEFAULT_TIMEOUT = 5000;
However, uppercase naming is a convention, not a special JavaScript feature.
This:
const API_URL = "...";
is not more “constant” than:
const apiUrl = "...";
The const keyword provides the language-level restriction.
Is const Faster Than let?
It is not correct to assume that const is always faster than let.
Modern JavaScript engines perform many optimizations internally. In normal application development, choosing between const and let should primarily be based on correctness, clarity, and whether reassignment is required, rather than expected performance differences.
Use the declaration that best communicates how the variable is intended to behave.
Does const Improve Security?
const can make code safer in the sense that it prevents accidental reassignment of a binding.
For example:
const API_URL = "https://example.com";
Other code in the same scope cannot simply replace that binding.
However, const is not a security mechanism. It does not protect secrets, encrypt data, or prevent malicious code from modifying objects.
Never place sensitive credentials or private API keys in client-side JavaScript merely because they are declared with const.
Practical Example
Here is a realistic example using several const declarations:
const productName = "Laptop";
const price = 50000;
const quantity = 2;
const discount = 0.10;
const subtotal = price * quantity;
const discountAmount = subtotal * discount;
const finalPrice = subtotal - discountAmount;
console.log(productName);
console.log("Subtotal:", subtotal);
console.log("Discount:", discountAmount);
console.log("Final Price:", finalPrice);
Here, none of the calculated bindings needs to be reassigned, so const is appropriate.
const With DOM Elements
const is commonly used when selecting an element from a webpage:
const button = document.querySelector("#submitButton");
button.addEventListener("click", () => {
console.log("Button clicked");
});
The button binding does not need to point to another element, so const is a good choice.
const With API Data
Suppose an application receives data from an API:
const response = await fetch("/api/users");
const users = await response.json();
console.log(users);
Both response and users are often declared using const when their bindings do not need reassignment.
The contents of users may still be mutable if it is an object or array.
const With Configuration
Configuration values are another common use case:
const config = {
language: "en",
theme: "dark",
timeout: 5000
};
console.log(config.theme);
The configuration object can still be modified:
config.theme = "light";
If the configuration should not be changed, consider freezing it:
const config = Object.freeze({
language: "en",
theme: "dark",
timeout: 5000
});
A Simple Way to Remember const
Think of const as protecting the variable binding, not necessarily the data structure stored inside it.
For a primitive:
const age = 25;
You cannot replace 25 with another value.
For an object:
const person = {
name: "Amit"
};
You cannot make person refer to another object, but you can normally modify person.name.
This distinction makes const much easier to understand.
Advantages of const
Using const provides several benefits:
- It prevents accidental reassignment.
- It is block-scoped.
- It encourages predictable code.
- It makes developer intentions clearer.
- It works well with modern JavaScript features.
- It is useful with objects, arrays, functions, and destructuring.
- It avoids many problems associated with
var. - It works naturally with modern modules.
- It improves code readability and maintainability.
Limitations of const
Despite its name, const does not provide complete immutability.
Important limitations include:
- Objects can still be mutated.
- Arrays can still be modified.
- Nested objects are not automatically frozen.
- It must be initialized during declaration.
- The binding cannot be reassigned.
- It does not provide security for sensitive information.
Understanding these limitations prevents many common programming mistakes.
Frequently Asked Questions About JavaScript const
What does const mean in JavaScript?
const declares a block-scoped variable whose binding cannot be reassigned after initialization.
Can a const variable be changed?
A const binding cannot be reassigned. However, if it contains an object or array, the object’s or array’s contents can usually be modified.
Can I declare const without initializing it?
No. A const declaration must have an initializer.
Is const block-scoped?
Yes. const is block-scoped.
Can I redeclare a const variable?
No. A const variable cannot be redeclared in the same scope.
Can a const array be modified?
Yes. You can modify its elements or use methods such as push() and pop(). You cannot assign a completely new array to the variable.
Can a const object be modified?
Yes. Its properties can normally be changed, added, or removed. const does not automatically freeze the object.
Is const better than let?
Neither is universally better. Use const when the binding does not need reassignment. Use let when reassignment is required.
Is const better than var?
For most modern JavaScript code, const and let are preferred because they are block-scoped and avoid several problematic behaviors associated with var.
Does const make a variable immutable?
Not necessarily. It prevents reassignment of the binding, but objects and arrays referenced by a const variable can still be mutable.
What happens when I reassign a const variable?
JavaScript throws a TypeError when an attempt is made to assign a new value to an existing const binding.
What is the Temporal Dead Zone?
The Temporal Dead Zone is the period between entering a scope and reaching the declaration of a let or const variable. Accessing the variable during this period results in a ReferenceError.
When should I use const?
Use const by default when you do not need to reassign the variable. Switch to let when the variable needs to change.
Final Thoughts
JavaScript const is a simple keyword, but understanding exactly what it does is important for writing reliable modern JavaScript.
The most important point to remember is that const prevents reassignment of a variable binding; it does not automatically make referenced objects or arrays immutable.
For example:
const name = "Amit";
cannot be reassigned.
But:
const user = {
name: "Amit"
};
user.name = "Rahul";
is allowed because the object itself has not been replaced.
A practical modern JavaScript approach is to use const whenever a binding does not need reassignment and use let when reassignment is necessary. Avoid var in new code unless you have a specific reason to use its older scoping behavior.
Once you understand scope, reassignment, objects, arrays, destructuring, and the Temporal Dead Zone, const becomes one of the easiest and most useful JavaScript features to work with.