JavaScript > JavaScript Fundamentals > Variables and Constants > const declarations

Understanding const Declarations in JavaScript

This snippet demonstrates the usage of const for declaring constants in JavaScript, highlighting their immutability and scope.

Basic const Declaration

The const keyword declares a constant variable, meaning its value cannot be reassigned after it's initialized. Trying to change the value of a const variable will result in a TypeError. However, const doesn't mean the value is immutable, just that the variable identifier cannot be reassigned. This distinction is important when working with objects and arrays.

// Declaring a constant variable
const PI = 3.14159;

// Attempting to reassign a const variable will result in an error
// PI = 3.14; // This will throw a TypeError: Assignment to constant variable.

console.log("The value of PI is: " + PI);

const with Objects and Arrays

While the const declaration prevents reassignment of the variable, it does not make the underlying object or array immutable. You can still modify the properties of an object or the elements of an array declared with const. Only reassigning the variable to a completely new object or array is prohibited.

// Declaring a const object
const person = { name: "John", age: 30 };

// You CAN modify the properties of the object
person.age = 31;  // This is allowed
person.city = "New York"; // This is also allowed

console.log(person);

// Attempting to reassign the object itself will result in an error
// person = { name: "Jane", age: 25 }; // This will throw a TypeError

// Declaring a const array
const numbers = [1, 2, 3];

// You CAN modify the contents of the array
numbers.push(4); // This is allowed
numbers[0] = 10; // This is also allowed

console.log(numbers);

// Attempting to reassign the array itself will result in an error
// numbers = [4, 5, 6]; // This will throw a TypeError

Scope of const

const variables have block scope, meaning they are only accessible within the block of code where they are defined (e.g., inside an if statement, a for loop, or a function). If you declare a const variable with the same name in a nested block, it creates a new variable that shadows the outer one within that block. This avoids accidental modification of outer variables.

function example() {
  const message = "Hello!";

  if (true) {
    const message = "Goodbye!"; // This is a different 'message' variable in a new scope
    console.log("Inside if block: " + message); // Output: Goodbye!
  }

  console.log("Outside if block: " + message); // Output: Hello!
}

example();

Real-Life Use Case

const is ideal for configuration settings that should not change during the execution of a program. For example, API keys, database connection strings, or mathematical constants (like PI) are excellent candidates for const declarations. Using const helps prevent accidental modification of these critical values, leading to more robust and predictable code.

Best Practices

Use const by default for variables that should not be reassigned. This improves code readability and helps prevent errors. Only use let when you know a variable's value needs to change.

Interview Tip

Be prepared to explain the difference between const, let, and var. Focus on the scope (block vs. function) and mutability (reassignment vs. modification of properties). Also, highlight the fact that const doesn't create immutable objects, only immutable bindings.

When to Use const

Use const when you want to declare a variable whose value will not change after it's initially assigned. This helps improve code maintainability and prevent unexpected behavior by making it clear that the variable is intended to be a constant.

Memory Footprint

The memory footprint of a const variable is generally the same as a let or var variable holding the same type of data. The keyword const primarily enforces the rule of no reassignment; it doesn't inherently affect the memory allocation or garbage collection differently.

Alternatives

If you need a truly immutable object or array (where even the properties or elements cannot be changed), consider using methods or libraries that provide immutable data structures, such as Object.freeze() or libraries like Immutable.js. These options provide stronger guarantees of immutability but come with a performance cost.

Pros

  • Prevents accidental reassignment of variables.
  • Improves code readability by clearly indicating which variables are intended to be constants.
  • Helps catch errors early during development.
  • Cons

  • Does not make objects or arrays truly immutable. Only prevents reassignment.
  • Can lead to confusion if developers misunderstand the difference between immutability and preventing reassignment.
  • FAQ

    • What happens if I try to reassign a const variable?

      You will get a TypeError indicating that you cannot assign a value to a constant variable.
    • Can I modify the properties of an object declared with const?

      Yes, you can modify the properties of an object declared with const. The const declaration only prevents you from reassigning the variable to a completely different object.
    • Is const supported in all JavaScript environments?

      Yes, const is supported in all modern JavaScript environments (browsers and Node.js).