Introduction to const in JavaScript

The const keyword in JavaScript, introduced in ES6 (ECMAScript 2015), is used to declare constants. A constant is a variable whose value cannot be reassigned once it is initialized. This makes const an excellent choice for values that should remain constant throughout the program. It ensures better code reliability and readability by preventing accidental changes.

Key Features of const

Constant Value
Variables declared with const must be initialized at the time of declaration and cannot be reassigned.

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

Block-Level Scope
Like let, const has block-level scope, meaning it is only accessible within the block where it is defined.

{
const name = "John";
console.log(name); // Output: John
}
// console.log(name); // Error: name is not defined

No Redeclaration
Variables declared with const cannot be redeclared in the same scope.

const age = 30;
// const age = 35; // Error: Identifier 'age' has already been declared

Works with Objects and Arrays
While the reference of an object or array declared with const cannot be changed, the content of the object or array can be modified.

const person = { name: "Alice", age: 25 };
person.age = 26; // Allowed
console.log(person); // Output: { name: 'Alice', age: 26 }

Syntax of const

The syntax for declaring a constant is simple:

const variableName = value;
  • variableName: The name of the constant, adhering to JavaScript naming rules.
  • value: The initial value of the constant (required).

Examples of Using const

Example 1: Declaring a Constant

const gravity = 9.8;
console.log(gravity); // Output: 9.8

Example 2: Constant in Block Scope

if (true) {
const day = "Monday";
console.log(day); // Output: Monday
}
// console.log(day); // Error: day is not defined

Example 3: Objects and const

const car = { brand: "Toyota", color: "red" };
car.color = "blue"; // Modifying the object property is allowed
console.log(car); // Output: { brand: 'Toyota', color: 'blue' }

Example 4: Arrays and const

const numbers = [1, 2, 3];
numbers.push(4); // Adding elements to the array is allowed
console.log(numbers); // Output: [1, 2, 3, 4]

// numbers = [5, 6]; // Error: Assignment to constant variable

Differences Between const, let and var

Featureconstletvar
ScopeBlock-levelBlock-levelFunction-level
ReassignmentNot allowedAllowedAllowed
HoistingNo usable hoistingNo usable hoistingHoisted (undefined initially)
RedeclarationNot allowed in the same scopeNot allowed in the same scopeAllowed

Best Practices for Using const

Use const by Default
Always prefer const for variables that do not require reassignment. This improves code stability.

Combine const with Descriptive Names
Use clear and descriptive names for constants to improve readability.

const MAX_USERS = 100;

Avoid Using const for Reassignable Data
If you need to reassign values, use let instead of const.

Common Mistakes with const

Skipping Initialization
A const variable must always be initialized when declared.

// const pi; // Error: Missing initializer in const declaration

Attempting Reassignment
Once a constant is defined, reassigning it will throw an error.

const name = "Emma";
// name = "Sophia"; // Error: Assignment to constant variable

Misunderstanding Mutability of Objects
Declaring an object with const does not make the object immutable, only its reference.

const obj = { key: "value" };
obj.key = "newValue"; // Allowed

Why Use const?

  • Prevent Bugs: It eliminates accidental reassignment, making your code more predictable.
  • Readable Code: Using const makes it clear to other developers which variables should not change.
  • Better Performance: The use of const can help JavaScript engines optimize code more effectively.

When to Use const

  • When declaring variables that should not be reassigned, such as configuration values or constants.
  • For objects or arrays where the structure remains consistent, but the contents may change.

Leave a Comment