Are there constants in JavaScript? If not, what is the common practice for specifying variables that are used as constants?
JavaScript does have constants through the const keyword introduced in ES6, though they work differently than constants in many other programming languages. The const declaration creates a read-only reference to a value, meaning the variable identifier cannot be reassigned, but the value itself (especially for objects and arrays) can still be mutated. For true immutability, additional techniques are often required.
Contents
- Understanding JavaScript Constants
- Key Differences from Traditional Constants
- Common Practices for Constants
- Immutability vs. const
- Best Practices and Recommendations
Understanding JavaScript Constants
The const keyword in JavaScript was introduced with ES6 and provides a way to declare variables that cannot be reassigned. When you declare a variable with const, you create a read-only reference to a value.
const PI = 3.14159;
// PI = 3.14; // This would throw an error: "Assignment to constant variable"
As the Mozilla Developer Network explains, “The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned.”
Key Differences from Traditional Constants
JavaScript constants differ significantly from constants in languages like C++ or Java:
- Reference vs. Value Immutability:
constprevents reassignment of the reference, not mutation of the referenced value- For objects and arrays, the contents can still be modified
const person = {name: "John", age: 30};
person.age = 31; // This works - the object content is mutable
// person = {name: "Jane"}; // This would throw an error - reassignment not allowed
- Initialization Requirement:
constvariables must be initialized at declaration time- Unlike
var, you cannot declare aconstwithout assigning a value
const MAX_SIZE; // SyntaxError: Missing initializer in const declaration
const MAX_SIZE = 100; // Valid
- Block Scope:
consthas block scope likelet, not function scope likevar
Common Practices for Constants
Naming Conventions
The most common practice for naming constants in JavaScript is to use ALL_CAPS with underscores, following the convention from languages that have true constants:
const MAX_REQUEST_SIZE = 1024 * 1024; // 1MB
const API_ENDPOINT = "https://api.example.com/v1";
const DEFAULT_TIMEOUT = 5000;
As noted in the Udacity blog post, “best practices include making constants all uppercase; your local conventions may differ.”
Usage Patterns
-
Primitive Values: Use
constfor primitive values that shouldn’t change:javascriptconst PI = 3.14159; const GRAVITY = 9.81; const APP_VERSION = "1.2.3"; -
Configuration and Settings: Store application constants in dedicated files:
javascript// config/constants.js export const API_BASE_URL = "https://api.example.com"; export const MAX_RETRIES = 3; export const DEFAULT_TIMEOUT = 5000; -
Object and Array Constants: Even though the contents are mutable,
constis still preferred to prevent reassignment:javascriptconst DEFAULT_CONFIG = { theme: "dark", notifications: true, languages: ["en", "es", "fr"] };
Immutability vs. const
This is a crucial distinction that many JavaScript developers misunderstand. As several sources emphasize, const does not provide immutability.
What const Actually Does
- Prevents reassignment of the variable reference
- Works perfectly for primitive values (which are already immutable)
- Does not prevent mutation of object/array contents
True Immutability Techniques
For actual immutability, you need additional approaches:
-
Object.freeze(): Makes an object immutable
javascriptconst frozenConfig = Object.freeze({ theme: "dark", notifications: true }); // frozenConfig.theme = "light"; // Throws error in strict mode -
Immutable Data Libraries: Libraries like Immutable.js or Immer provide true immutability
-
Deep Freezing: For nested objects
javascriptfunction deepFreeze(obj) { Object.freeze(obj); Object.getOwnPropertyNames(obj).forEach(prop => { if (obj[prop] && typeof obj[prop] === "object") { deepFreeze(obj[prop]); } }); }
As Mathias Bynens explains, “ES2015 const is not about immutability.”
Best Practices and Recommendations
General Guidelines
-
Use
constby default: As recommended by the MDN style guide, “use const over let whenever a variable is not reassigned in its scope.” -
Only use
letwhen necessary: If you know a variable will need to be reassigned, uselet -
Avoid
varin modern code:varhas function scope and hoisting behavior that can lead to bugs
Practical Examples
Good Practice:
// Configuration constants
const API_BASE_URL = "https://api.example.com";
const MAX_RETRIES = 3;
const TIMEOUT_MS = 5000;
// Function that processes data
function processData(data) {
const processed = data.map(item => transform(item));
return processed.filter(item => item.isValid);
}
Avoid:
// Using var for constants (not recommended)
var API_BASE_URL = "https://api.example.com";
var MAX_RETRIES = 3;
// Using let unnecessarily (const would be better)
let apiUrl = "https://api.example.com";
// apiUrl never gets reassigned, so const would be clearer
When to Use const vs let
| Use Case | const |
let |
|---|---|---|
| Primitive value that won’t change | ✓ | ✗ |
| Object/array reference (even if contents change) | ✓ | ✗ |
| Variable that will be reassigned | ✗ | ✓ |
| Variable in a loop | ✗ | ✓ |
| Variable whose value might change based on conditions | ✗ | ✓ |
Project Organization
For larger projects, organize constants in a dedicated structure:
// src/constants/index.js
export const API = {
BASE_URL: "https://api.example.com",
ENDPOINTS: {
USERS: "/users",
POSTS: "/posts"
}
};
export const CONFIG = {
MAX_RETRIES: 3,
TIMEOUT_MS: 5000,
CACHE_TTL: 3600
};
export const THEMES = {
LIGHT: "light",
DARK: "dark",
AUTO: "auto"
};
As noted in the Medium article on JavaScript project architecture, “The constants/ folder has an index.js file, which creates a clean interface in your code.”
Conclusion
JavaScript does have constants through the const keyword, but they work differently than constants in many other programming languages. The key takeaways are:
- Use
constfor variables that won’t be reassigned - this is the modern JavaScript best practice - Remember that
constdoesn’t provide true immutability - it prevents reassignment but not mutation of object contents - Follow naming conventions - use ALL_CAPS with underscores for constant names
- For true immutability - use
Object.freeze()or immutable data libraries - Organize constants - create dedicated files/folders for better code organization
By following these practices, you’ll write more predictable, maintainable JavaScript code while avoiding common pitfalls related to variable scoping and mutability.
Sources
- const - JavaScript | MDN
- Explain Constants in ES6 | GeeksforGeeks
- JavaScript Constants — Fortresses Against Confusion | Udacity
- ES2015 const is not about immutability · Mathias Bynens
- JavaScript Project Architecture: Constants | Medium
- Understanding const and Immutability | Otee’s Notes
- Once and for all: const in JavaScript is not immutable - DEV Community
- JavaScript const - GeeksforGeeks