Skip to main content

The const Keyword

In JavaScript, the const keyword is used to declare a constant variable. Once a value is assigned to a constant, it cannot be reassigned or redeclared.

const pi = 3.14;

Here, we use const to declare a constant variable named pi and assign it the value 3.14. The value of pi remains constant throughout the program, and any attempt to reassign it will result in an error.

Example:

const pi = 3.14;
pi = 3.14159; // Error: Assignment to constant variable

Attempting to reassign a value to a constant variable, as shown above, will result in a runtime error.

Benefits of const

  • Immutable Values: Variables declared with const are immutable, meaning their values cannot be changed after assignment. This makes const suitable for situations where a constant value is expected.

  • Block Scoping: Similar to let, variables declared with const are block-scoped. They are limited to the block, statement, or expression they are defined in.

Use Cases for const

const daysInWeek = 7;
const gravity = 9.8;

const user = {
name: "John",
age: 25,
};

Constants are often used for values that remain unchanged throughout the program, such as mathematical constants, days in a week, or configuration values.

Considerations

  • Initialization Required: A const variable must be initialized with a value at the time of declaration.

  • Object Properties: While the reference to the object itself is constant, the properties of a const object can still be modified.

const person = {
name: "Alice",
age: 30,
};

person.age = 31; // Valid: Modifying object property

In future chapters, we'll explore more scenarios and best practices for using the const keyword in JavaScript.