The const keyword is used to declare variables whose binding should not be
reassigned. In modern JavaScript, const is often the best first choice
when you create a variable and do not plan to give that variable a completely new
value later.
const in JavaScriptUse const when a variable should keep the same assigned reference after it
is created. This makes your code more predictable and helps protect against accidental
reassignment.
const siteName = "RedoHub";
const taxRate = 15;
console.log(siteName);
Here, siteName and taxRate are declared with
const because they are meant to stay fixed.
const Must Be Assigned a ValueUnlike let, a const variable must receive a value at the time
it is declared.
const country = "Bangladesh";
This is valid. But the following is not valid:
// const country; // Error
const variable cannot be declared without a
value. JavaScript requires an assignment immediately.
const Cannot Be ReassignedOnce a variable is declared with const, you cannot assign a completely new
value to that variable name.
const pi = 3.1416;
// pi = 3.14; // Error
This rule makes const a strong choice for values that should stay stable
throughout the program.
let instead
of const.
constLike let, const is block-scoped. A variable declared inside a
block exists only inside that block.
if (true) {
const message = "Welcome";
console.log(message);
}
// console.log(message); // Error
This means message is only available inside the if block.
const and ArraysA common beginner confusion is this: const does not mean the contents of an
array can never change. It means the variable itself cannot be reassigned to a
different array.
const colors = ["red", "green", "blue"];
colors[0] = "yellow";
colors.push("black");
console.log(colors);
This works because the array itself still exists under the same variable name. You are changing the contents, not reassigning the variable.
const and ObjectsThe same idea applies to objects. A const object can have its properties
changed, but the variable cannot be reassigned to a different object.
const user = {
name: "Nabila",
age: 22
};
user.age = 23;
console.log(user);
const protects the variable binding, not the inner
contents of arrays or objects.
const vs letBoth const and let are modern ways to declare variables, but
they are used in different situations.
| Feature | const |
let |
|---|---|---|
| Reassignment | Not allowed | Allowed |
| Must have value at declaration | Yes | No |
| Scope | Block scope | Block scope |
| Best use | Stable values | Changing values |
Many developers prefer to use const by default and switch to
let only when they know a variable will change. This creates safer and
more intentional code.
const is used for variables that should not be reassignedconst variable must be assigned a value immediatelyconst is block-scoped, just like letconst variable to a new valueconst can still have their contents changedconst by default when the variable is meant to stay stable