JavaScript Const

In JavaScript, const is a keyword used to declare variables whose values are intended to remain constant throughout the life of the program. It was introduced in ES6 (ECMAScript 2015) and offers block-scoped constants.

Key Features of const:

1. Block Scope

Variables declared with const are block-scoped, meaning they are accessible only within the block {} where they are defined, similar to let.

Example:

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

Try It Now

2. No Re-assignment

A variable declared with const cannot be reassigned after its initial value is set. Attempting to do so will result in an error.

Example:

const gravity = 9.8;
// gravity = 10; // Error: Assignment to constant variable

Try It Now

3. Must Be Initialized

Unlike let and var, const variables must be initialized at the time of declaration. You cannot declare a const variable without assigning a value to it.

Example:

// const speed; // Error: Missing initializer in const declaration
const speed = 120;

Try It Now

4. Objects and Arrays with const

Although const prevents re-assignment, it does not make objects or arrays immutable. You can still modify the properties of an object or the elements of an array.

Example with Objects:

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

Try It Now

Example with Arrays:

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

Try It Now

Best Practices

  • Use const when you do not want the variable to be reassigned.
  • It helps signal to other developers that the value should remain constant.
  • Use it for values that should not change, like configuration settings or fixed values.

Summary

  • const is block-scoped and immutable in terms of re-assignment.
  • It ensures that the reference cannot be changed, though the data the reference points to can be modified.
  • Using const can make code easier to understand and maintain by clearly indicating which variables are not meant to change.