JavaScript const Keyword
Subject: JavaScript
The const keyword in JavaScript is used to declare variables that cannot be reassigned after their initial value is set. It was introduced in ES6 (ECMAScript 2015) and is ideal for values that remain constant throughout your program.
Syntax
Example: Declaring with const
Key Features of const
1. Block Scope
Like let, const is block-scoped and only accessible within the block it is defined in.
2. Cannot Be Reassigned
Once a value is assigned to a const variable, it cannot be changed.
3. Constant ≠ Immutable
You can modify the contents of objects or arrays declared with const, but not reassign them.
4. Must Be Initialized
const declarations must include an initial value.
Best Practices
- Use
constby default - Use
letonly when reassignment is needed - Prefer
constto avoid unintended variable updates - Use with objects and arrays whose reference shouldn't change
Key Takeaways
constcreates read-only variables- Reassignment is not allowed, but object mutation is
- It provides block-level scoping
- Must be initialized at the time of declaration
- Promotes safer, more predictable code
- Recommended for constants and fixed references