Topic 8 of 37
The const Keyword
Overview
The 'const' keyword is used to declare variables whose bindings cannot be reassigned. By default, you should always use 'const' unless you know the value will change. This makes your code more predictable and prevents accidental reassignments, which is a common source of bugs.
Syntax
'const' creates an immutable binding, not an immutable value. You cannot reassign the identifier, but you can mutate the contents of objects or arrays it points to.
Constant Binding
javascript
const API_URL = "https://api.example.com";
// API_URL = "https://new.com"; // TypeError: Assignment to constant variable.
const user = { name: "Alice" };
user.name = "Bob"; // This is ALLOWED!Common Pitfalls
- Forgetting to initialize a 'const' variable upon declaration (SyntaxError: Missing initializer in const declaration).
Interview Tips
- Interviewers will often ask if 'const' makes an object immutable. The answer is NO. To make an object immutable, you need Object.freeze().
Real-World Example
Using const for environment variables or fixed configuration.
example
javascript
const MAX_RETRIES = 3;
let attempts = 0;
while(attempts < MAX_RETRIES) {
// try request
attempts++;
}