In JavaScript, the const
keyword is used to declare a constant variable, which means the variable cannot be reassigned after it has been initialized. Here are some key points about using const
in JavaScript:
Declaration and Initialization:
javascriptconst myConstant = 42;
When you use const
, you must initialize the variable at the time of declaration.
Reassignment is Not Allowed:
javascriptconst myConstant = 42;
// This will result in an error
myConstant = 20;
Once a variable is declared using const
, you cannot reassign it.
Block Scope:
Like let
, const
is block-scoped. It means it is only accessible within the block or statement on which it is defined.
javascriptif (true) {
const blockScoped = "I am inside the block";
}
// This will result in an error
console.log(blockScoped);
Object and Array Constants:
While const
prevents the reassignment of the variable itself, it doesn't make the values within an object or array immutable.
javascriptconst myArray = [1, 2, 3];
myArray.push(4); // This is allowed
const myObject = { key: "value" };
myObject.key = "new value"; // This is allowed
If you want to make the values within an object or array immutable, you would need to use other techniques like Object.freeze()
or libraries like Immutable.js.
Use in Loops:
const
can be useful in loops to declare loop variables that should not be reassigned.
javascriptfor (const i = 0; i < 5; i++) {
// This will result in an error because i cannot be reassigned
}
Constants in Uppercase: It is a common convention to use uppercase letters for constant variables.
javascriptconst MY_CONSTANT = 100;
This makes it easier to identify constants in your code.
Remember that const
doesn't make the variable or its contents truly immutable, it just prevents the variable from being reassigned. If you want to achieve immutability at a deeper level, you would need to use other techniques or libraries.