JavaScript const Keyword
Learn how to declare constant variables in JavaScript using ES6 with clear examples and best practices.
The const keyword was introduced in ES6 (ECMAScript 2015) and is used to
declare variables whose values are intended to remain constant throughout the execution of a program.
Once assigned, a const variable cannot be reassigned.
Prior to ES6, JavaScript developers primarily relied on the
var keyword. However, var-declared variables can be
redeclared and reassigned, which often leads to unexpected behavior and bugs in large-scale applications.
The key difference is that variables declared with
const cannot be reassigned, whereas variables declared using
var or let can be updated after their initial declaration.
Using const improves code readability and maintainability by clearly indicating which
values should never change. It is commonly used for configuration settings, fixed values,
mathematical constants, and references that should remain stable.
Declaring and Initializing a const Variable
In JavaScript, a const variable must be declared and initialized at the same time.
Attempting to declare a constant without assigning a value will result in a syntax error.
Example: Using the JavaScript const Keyword
JavaScript Example
const x = 16;
console.log("The value of the constant variable x is: " + x);
Try it Yourself ยป
Properties of const Variables
Below are the most important characteristics and behaviors of variables declared using the
const keyword in JavaScript. Understanding these properties will help you
write safer, more predictable, and maintainable code.
-
A variable declared with the
constkeyword cannot be reassigned. Once a value is assigned, the variable identifier cannot point to a different value. -
A
constvariable must be initialized at the time of declaration.
Example:const x = 6; -
You cannot declare a
constvariable without assigning a value. Attempting to do so will result in a syntax error. -
The value assigned to a
constvariable cannot be changed through reassignment. Any attempt to reassign it will throw a runtime error. -
Variables declared with
consthave block scope. This means they are only accessible within the block in which they are defined, such as insideif,for, orwhilestatements. -
The
constkeyword is subject to the temporal dead zone. It cannot be accessed before its declaration, unlikevar, which is hoisted. -
When a
constvariable is assigned an array, you can modify the contents of the array, but you cannot reassign the array itself. -
A
constdeclaration creates a constant reference to a value, not an immutable value. This distinction is important when working with objects and arrays. -
For objects declared using
const, object properties can be added, removed, or modified, but the object reference itself cannot be reassigned.
Examples of const in JavaScript
The following practical examples demonstrate how the const keyword behaves
in real-world JavaScript scenarios. These examples highlight reassignment rules, scope behavior,
and common use cases.
Example 1: Preventing Reassignment with const
This example shows that a variable declared with const cannot be reassigned after
its initial value is set.
const MAX_USERS = 100;
MAX_USERS = 150; // TypeError
Constants are ideal for values that should never change, such as configuration limits, API endpoints, or fixed application settings.
Example 2: Block Scope Behavior of const
This example demonstrates that const variables are block-scoped.
Each block can define its own constant without affecting others.
const role = "User";
if (true) {
const role = "Admin";
console.log("Inside block:", role);
}
console.log("Outside block:", role);
Try it Yourself ยป
Because const is block-scoped, variables declared inside a block
are isolated from the outer scope, reducing the risk of accidental overwrites.
Example 3: const and the Temporal Dead Zone
This example demonstrates that const variables are hoisted but
cannot be accessed before their declaration.
Accessing them early results in a runtime error due to the Temporal Dead Zone (TDZ).
console.log(apiUrl);
const apiUrl = "https://example.com/api";
Try it Yourself ยป
Unlike var, const variables exist in a
temporal dead zone from the start of the block until their declaration
is evaluated, preventing access before initialization.
Example 4: const Variables Require Immediate Initialization
This example shows that a const variable must be initialized
at the moment it is declared. Declaring it without a value is not allowed.
const PORT;
PORT = 3000;
Try it Yourself ยป
Because const variables are designed to remain constant,
JavaScript enforces initialization at declaration to ensure predictable behavior.
Example 5: Using const with Arrays
When an array is declared using const, the array reference remains constant,
but its contents can still be modified.
const supportedBrowsers = ["Chrome", "Firefox", "Safari"];
// Add a new browser
supportedBrowsers.push("Edge");
// Update an existing value
supportedBrowsers[1] = "Firefox ESR";
console.log(supportedBrowsers);
Try it Yourself ยป
Although the array contents can be changed, attempting to reassign
supportedBrowsers to a new array will result in an error.
Example 6: Using const with Objects
Objects declared with const maintain a constant reference,
but their properties can be updated as needed.
const userProfile = {
name: "Emma Johnson",
role: "Frontend Developer",
experience: 3
};
// Update object properties
userProfile.role = "Senior Frontend Developer";
userProfile.experience += 2;
console.log(userProfile);
Try it Yourself ยป
While you cannot reassign the userProfile object itself,
modifying its properties is allowed and commonly used in real-world applications.