JavaScript Const

The const keyword in JavaScript is used to declare variables that cannot be reassigned after their initial declaration. Variables declared with const are block-scoped, similar to let, and must be initialized during declaration.

Key Topics

Immutable Values

Variables declared with const cannot be reassigned. However, this does not mean the value is immutable; for objects and arrays, their contents can still be modified.

const x = 10;
// x = 20; // Error: Assignment to constant variable
console.log(x);

Output

> 10

Block Scope

Similar to let, const variables are block-scoped and are only accessible within the block in which they are declared.

{
    const pi = 3.14;
    console.log(pi); // Inside the block
}
// console.log(pi); // Error: pi is not defined outside the block

Output

> 3.14

> ReferenceError: pi is not defined

Constant Objects

For objects declared with const, you cannot reassign the object itself, but you can modify its properties.

const person = { name: "John", age: 30 };
person.age = 31; // Allowed: Modifying properties
console.log(person);

Output

{ name: "John", age: 31 }

Examples of Using Const

Below is a practical example demonstrating the use of const in arrays and objects.

const numbers = [1, 2, 3];
numbers.push(4); // Allowed: Modifying array content
console.log(numbers);

const car = { brand: "Toyota" };
car.model = "Corolla"; // Allowed: Adding properties
console.log(car);

Output

[1, 2, 3, 4]

{ brand: "Toyota", model: "Corolla" }

Key Takeaways

  • Immutable Assignment: const prevents reassignment of variables but allows modification of object and array contents.
  • Block Scope: Variables declared with const are limited to the block where they are defined.
  • Initialization: Variables declared with const must be initialized during declaration.
  • Best Practice: Use const for values that should not be reassigned.