DEV Community

Cover image for JavaScript const Keyword Explained: Syntax, Rules, Examples, and Best Practices
Rachit Joshi
Rachit Joshi

Posted on

JavaScript const Keyword Explained: Syntax, Rules, Examples, and Best Practices

Introduction

JavaScript provides several ways to declare variables, including var, let, and const.

Among these, const is one of the most commonly used keywords in modern JavaScript development because it helps developers write cleaner and more secure code.

**
What Is const in JavaScript?**

The const keyword is used to declare variables whose values cannot be reassigned after they have been initialized.

Here's the basic syntax:

const variableName = value;
Example
const language = "JavaScript";

console.log(language);

Output:

JavaScript

Why Should You Use const?

There are several advantages to using the const keyword:

It prevents accidental reassignment.
It makes code easier to understand.
It improves code reliability.
It follows modern JavaScript development practices.
Rules of the const Keyword

  1. Variables must be initialized.

A value must be assigned when the variable is created.

const age = 25;

The following example will produce an error:

const age;

  1. Reassignment is not allowed. const country = "India";

country = "Japan";

This code generates an error because the value cannot be changed after declaration.

  1. const uses block scope. { const number = 100; console.log(number); }

Variables declared inside a block remain accessible only within that block.

Difference Between var, let, and const
Keyword Scope Can Be Reassigned
var Function scope Yes
let Block scope Yes
const Block scope No
Using const with Objects

Even though the variable itself cannot be reassigned, the contents of an object can still be modified.

const user = {
name: "John"
};

user.name = "David";

console.log(user.name);

Output:

David
Using const with Arrays

You can also modify the elements inside an array.

const fruits = ["Apple", "Mango"];

fruits.push("Orange");

console.log(fruits);

Output:

["Apple", "Mango", "Orange"]
Best Practices

To make your code cleaner and easier to maintain, follow these practices:

Use const whenever possible.
Use let only when values need to change.
Avoid using var in modern projects.
Write descriptive variable names.

Conclusion

The const keyword is an essential part of modern JavaScript.

It helps developers avoid mistakes, improves code readability, and makes applications more reliable.

Whether you are a beginner or an experienced developer, understanding const is an important step toward mastering JavaScript.

Top comments (0)