NeuroAgent

JavaScript Constants: Complete Guide

Learn about JavaScript constants with the const keyword. Discover key differences from traditional constants, naming conventions, and techniques for true immutability in modern JavaScript development.

Are there constants in JavaScript? If not, what is the common practice for specifying variables that are used as constants?

NeuroAgent

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

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.

javascript
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:

  1. Reference vs. Value Immutability:
    • const prevents reassignment of the reference, not mutation of the referenced value
    • For objects and arrays, the contents can still be modified
javascript
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
  1. Initialization Requirement:
    • const variables must be initialized at declaration time
    • Unlike var, you cannot declare a const without assigning a value
javascript
const MAX_SIZE; // SyntaxError: Missing initializer in const declaration
const MAX_SIZE = 100; // Valid
  1. Block Scope:
    • const has block scope like let, not function scope like var

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:

javascript
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

  1. Primitive Values: Use const for primitive values that shouldn’t change:

    javascript
    const PI = 3.14159;
    const GRAVITY = 9.81;
    const APP_VERSION = "1.2.3";
    
  2. 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;
    
  3. Object and Array Constants: Even though the contents are mutable, const is still preferred to prevent reassignment:

    javascript
    const 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:

  1. Object.freeze(): Makes an object immutable

    javascript
    const frozenConfig = Object.freeze({
      theme: "dark",
      notifications: true
    });
    // frozenConfig.theme = "light"; // Throws error in strict mode
    
  2. Immutable Data Libraries: Libraries like Immutable.js or Immer provide true immutability

  3. Deep Freezing: For nested objects

    javascript
    function 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

  1. Use const by default: As recommended by the MDN style guide, “use const over let whenever a variable is not reassigned in its scope.”

  2. Only use let when necessary: If you know a variable will need to be reassigned, use let

  3. Avoid var in modern code: var has function scope and hoisting behavior that can lead to bugs

Practical Examples

Good Practice:

javascript
// 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:

javascript
// 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:

javascript
// 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:

  1. Use const for variables that won’t be reassigned - this is the modern JavaScript best practice
  2. Remember that const doesn’t provide true immutability - it prevents reassignment but not mutation of object contents
  3. Follow naming conventions - use ALL_CAPS with underscores for constant names
  4. For true immutability - use Object.freeze() or immutable data libraries
  5. 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

  1. const - JavaScript | MDN
  2. Explain Constants in ES6 | GeeksforGeeks
  3. JavaScript Constants — Fortresses Against Confusion | Udacity
  4. ES2015 const is not about immutability · Mathias Bynens
  5. JavaScript Project Architecture: Constants | Medium
  6. Understanding const and Immutability | Otee’s Notes
  7. Once and for all: const in JavaScript is not immutable - DEV Community
  8. JavaScript const - GeeksforGeeks