The Complete Guide for Using Constants in JavaScript

As a JavaScript developer, understanding how and when to use constants is crucial for writing clean, maintainable code. Constants allow you to declare variables whose values cannot be changed, helping prevent accidental reassignments and making your code more predictable.

In this comprehensive guide, we‘ll dive deep into the world of JavaScript constants. We‘ll explain what they are, how to declare and use them, and best practices and pitfalls to be aware of. By the end, you‘ll have a rock-solid grasp on leveraging constants to write better JavaScript. Let‘s get started!

What are Constants in JavaScript?

In JavaScript, a constant is a container for storing a value that is not intended to be reassigned throughout the execution of a program. Once a constant is initialized with a value, that value cannot be changed later on.

This is in contrast to variables declared with let or var, whose values can be freely reassigned at any point. For example:

let count = 1;
count = 2;
console.log(count); // 2 - no error

const MAX_COUNT = 100;
MAX_COUNT = 200; // TypeError: Assignment to constant variable

Attempting to reassign a constant will throw an error, protecting its value from accidental modification.

Why Use Constants?

Constants are useful for declaring and safeguarding values that should remain unchanged. Common examples include:

  • Configuration settings loaded from a file or API
  • Mathematical constants like PI or E
  • Enum-like sets of related, unchanging values
  • User-provided values that should not be modified
  • Sensitive information like API keys

According to a study by SEMrush, JavaScript is used by 97.6% of all websites. As codebases grow, using constants to store fixed values becomes increasingly important for code maintainability and bug prevention.

Placing values that should not change into appropriately named constants makes your code more readable and self-documenting. It signals to other developers (and your future self) not to modify those values elsewhere in the codebase. Hard-coding "magic values" in multiple places becomes a maintenance headache.

As Addy Osmani, Engineering Manager at Google, puts it:

"I use constants for any values I know won‘t change, such as configuration settings, mathematical constants like PI, or sets of unchanging values used in a lookup. It makes my code more readable and prevents accidental changes."

Declaring Constants with const

In JavaScript, constants are declared using the const keyword followed by the variable name and assigned value:

const API_URL = ‘https://api.example.com‘;
const PI = 3.14159;
const DEFAULT_COLOR = ‘#00FF00‘;
const WEEKDAYS = Object.freeze([‘Monday‘, ‘Tuesday‘, ‘Wednesday‘, ‘Thursday‘, ‘Friday‘]);

There are a few important rules to understand about declaring constants in JavaScript:

  1. Constants must be assigned a value when declared:
    const x; // SyntaxError: Missing initializer in const declaration
  2. Constants cannot be redeclared in the same scope:
    const x = 1;
    const x = 2; // SyntaxError: Identifier ‘x‘ has already been declared
  3. Constants are block-scoped, only accessible within the nearest enclosing block:
    if (true) {
    const x = 1;
    console.log(x); // 1
    }
    console.log(x); // ReferenceError: x is not defined 

Naming Constants

Constants are typically named using the upper snake case convention, with all uppercase letters and underscores separating words. This makes constants visually distinct from other variables.

const MAX_USERS = 100;
const GRAVITY = 9.81;
const BACKGROUND_COLOR = ‘#FAFAFA‘;

Adhering to this naming convention is considered a best practice in JavaScript development. It improves code readability and clearly communicates the intent of unchanging values.

Constants and Objects/Arrays

An important detail to understand is that constants are not deeply immutable when assigned an object or array. While the constant reference cannot be reassigned, the underlying object or array itself is still mutable:

const person = {
  name: ‘John‘
};

person.name = ‘Jane‘; // Allowed! Mutates property
person.age = 30; // Allowed! Adds new property

person = { name: ‘Alice‘ }; // Error! Cannot reassign the object

const numbers = [1, 2, 3];
numbers.push(4); // Allowed! Mutates the array
numbers = [4, 5 , 6]; // Error! Cannot reassign a new array

To create an immutable object or array, you can use the Object.freeze() method:

const person = Object.freeze({
  name: ‘John‘
});

const numbers = Object.freeze([1, 2, 3]);

person.name = ‘Jane‘; // TypeError: Cannot assign to read only property 
numbers.push(4); // TypeError: Cannot add property 3, object is not extensible

Freezing an object prevents new properties from being added and marks existing properties as non-writable. Be aware that Object.freeze() is shallow, so nested objects would need to be individually frozen.

According to the State of JavaScript 2020 survey, 85% of developers use const for declaring variables when they don‘t expect the value to change. Using Object.freeze() for complete immutability is less common but still a valuable tool to be aware of.

Declaring Constants Effectively

Let‘s walk through some more comprehensive examples to solidify our understanding of using constants in real-world JavaScript code.

Imagine we‘re building a web application that fetches user data from an API. We‘ll likely have some fixed values used throughout our code:

const API_BASE_URL = ‘https://api.example.com‘;
const RESULTS_PER_PAGE = 10;
const CACHE_EXPIRATION_MS = 3600000; // 1 hour in milliseconds

// Allowed HTTP methods for API requests
const HTTP_METHODS = Object.freeze({
  GET: ‘GET‘, 
  POST: ‘POST‘,
  PUT: ‘PUT‘,
  DELETE: ‘DELETE‘ 
});

Now let‘s use these constants in a function that fetches user data:

async function fetchUsers(page = 1) {
  const url = `${API_BASE_URL}/users?_page=${page}&_limit=${RESULTS_PER_PAGE}`;

  const response = await fetch(url, { method: HTTP_METHODS.GET });

  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }

  const data = await response.json();

  // Cache the response data
  localStorage.setItem(`users_page_${page}`, JSON.stringify(data));
  localStorage.setItem(`users_page_${page}_expiration`, Date.now() + CACHE_EXPIRATION_MS);

  return data;
}

Using constants improves this function‘s clarity and reusability:

  • API_BASE_URL, RESULTS_PER_PAGE, and HTTP_METHODS.GET are used to construct the API URL and fetch options.
  • CACHE_EXPIRATION_MS is used to set an expiration timestamp for caching the fetched data.
  • If the API URL or results per page need to change, we can update the constants in one place.

When Not to Use Constants

While constants are valuable, not every variable should be a constant. Use let for values that may change and const for values you expect not to change.

Overusing constants can make your code more verbose and harder to read, so aim for a balance. A codebase with too many unnecessary constants is just as difficult to maintain as one with too few.

Also, remember that constants are not a substitute for truly immutable data structures. For complex or nested data that needs true immutability, consider using a library like Immutable.js.

Constants Best Practices

To leverage constants effectively in your JavaScript code, follow these best practices:

  1. Use meaningful, descriptive names for constants. Avoid single-letter names or abbreviations.

  2. Declare constants as close to their usage as possible to keep their scope small.

  3. Use the upper snake case naming convention for constants to visually distinguish them from mutable variables.

  4. Don‘t hard-code values in your codebase. Extract them into appropriately named constants to improve readability and maintainability.

  5. If an object or array should be immutable, use Object.freeze() to prevent modifications.

  6. Only use constants for values that won‘t change during runtime. Don‘t use constants for variables that may be reassigned.

Conclusion

Constants are a powerful feature in JavaScript for creating variables with fixed, immutable values. By leveraging constants for configuration settings, enum-like sets, and other unchanging values, you can write cleaner, more maintainable, and less error-prone code.

In this guide, we covered the fundamentals of declaring constants, their scope and naming conventions, how to handle object/array immutability, and best practices to follow. We walked through detailed examples to illustrate constants in action.

Remember, while constants are invaluable, they‘re not a silver bullet. Aim for a balance and only use them for values that truly won‘t change during runtime. Avoid overusing constants for the sake of it.

To dive even deeper into JavaScript constants and other fundamentals, check out the following resources:

Now that you‘re armed with a rock-solid understanding of JavaScript constants, go forth and use them with confidence in your own code!

Similar Posts