Constant

Overview

A constant is an identifier for a value that cannot be modified during the execution of a program. Once a constant is assigned a value, that value remains fixed.

Core Concepts

  • Immutability: The core property of a constant; it prevents accidental changes to data that should remain static.
  • Naming Conventions: Often written in SCREAMING_SNAKE_CASE (e.g., MAX_RETRY_COUNT) to distinguish them from variables.
  • Compile-time vs. Runtime: Some constants are evaluated when the code is compiled, while others are set once when the program starts.

Code Examples

// TypeScript/JavaScript
const PI = 3.14159;
const API_BASE_URL = "https://api.example.com/v1";

// Attempting to reassign will cause a compile-time error
// PI = 3.14; // Error: Cannot assign to 'PI' because it is a constant.

Use Cases

  • Magic Numbers: Replacing arbitrary numbers in code with named constants to improve readability.
  • Configuration: Defining environment settings, timeout limits, or version numbers.
  • Mathematical Constants: Storing values like $\pi$ or $e$.

Gotchas

  • Reference Types: In languages like JavaScript or TypeScript, const prevents the reassignment of the variable identifier, but it does not make the object immutable. You can still modify properties of a constant object or elements of a constant array.
  • Overuse: Defining everything as a constant can lead to rigid code if the value actually needs to change based on user input or state.

Related Notes