JavaScript const
The const
keyword is used to declare constants in JavaScript. Constants are block-scoped, similar to variables declared using the let
keyword, but their value cannot be reassigned.
1. Declaring Constants
You can declare a constant using the const
keyword.
Example:
const pi = 3.14;
const gravity = 9.81;
console.log(pi); // Output: 3.14
console.log(gravity); // Output: 9.81
2. Block Scope
Constants declared with const
have block scope, meaning they are only available within the block they are defined in.
Example:
if (true) {
const blockScopedConst = "I am block scoped";
console.log(blockScopedConst); // Output: I am block scoped
}
// console.log(blockScopedConst); // This will cause an error
3. Reassigning Constants
Constants declared with const
cannot be reassigned. Attempting to do so will result in an error.
Example:
const pi = 3.14;
// pi = 3.14159; // This will cause an error
console.log(pi); // Output: 3.14
4. Mutable vs Immutable
While the value of a constant itself cannot be reassigned, the properties of objects and arrays declared with const
can be changed.
Example with Objects:
const person = {
name: "John",
age: 30
};
person.age = 31; // This is allowed
console.log(person); // Output: { name: 'John', age: 31 }
// person = {}; // This will cause an error
Example with Arrays:
const numbers = [1, 2, 3, 4, 5];
numbers.push(6); // This is allowed
console.log(numbers); // Output: [1, 2, 3, 4, 5, 6]
// numbers = [7, 8, 9]; // This will cause an error
5. Hoisting
Like variables declared with let
, constants declared with const
are not hoisted to the top of their block.
Example:
// console.log(hoistedConst); // This will cause an error
const hoistedConst = "This constant is not hoisted";
console.log(hoistedConst); // Output: This constant is not hoisted
6. Temporal Dead Zone
Similar to let
, constants declared with const
are subject to the temporal dead zone (TDZ), where accessing the constant before its declaration results in a ReferenceError.
Example:
function tdzExample() {
// console.log(tempConst); // ReferenceError: Cannot access 'tempConst' before initialization
const tempConst = "I am not accessible before my declaration";
console.log(tempConst); // Output: I am not accessible before my declaration
}
tdzExample();
7. Best Practices
- Use
const
for variables that should not be reassigned. - Use uppercase letters for constant names as a convention for values that are meant to be constants (e.g.,
const PI = 3.14;
). - Always declare constants at the top of their scope to avoid confusion.
By following these guidelines, you can write cleaner, more maintainable JavaScript code.