In JavaScript, the `const` keyword is used to declare constants, which are variables that cannot be re-assigned after their initial assignment. Here's how `const` is used in JavaScript:
Variable Declaration with `const`:
- Constants are declared using the `const` keyword followed by the variable name.
- Example:
javascript
const PI = 3.14; // Declaration of a constant named PI
const name = "John"; // Declaration of a constant named name
Assigning Values to `const` Variables:
- Constants must be assigned a value at the time of declaration, and once assigned, their value cannot be changed.
- Example:
javascript
const PI = 3.14;
console.log(PI); // Output: 3.14
PI = 3.14159; // Error: Assignment to constant variable
Block Scope:
- Constants declared with `const` have block scope, meaning they are only accessible within the block in which they are defined.
- Example:
javascript
if (true) {
const x = 10; // Block-scoped constant
console.log(x); // Output: 10
}
console.log(x); // Output: ReferenceError: x is not defined
Best Practices:
- Use `const` when you have values that should not be changed.
- Declare variables with `const` by default unless you explicitly need to reassign the value.
- Choose meaningful names for constants to improve code readability.
It's important to note that while the value of a `const` variable cannot be reassigned, it does not make the value itself immutable. If a constant holds an object or an array, the properties or elements within the object or array can still be modified. However, reassigning the constant variable itself is not allowed.
Using `const` helps convey your intent to keep a value unchanged and provides immutability where needed. It also helps prevent accidental reassignments and makes your code more maintainable.
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc