Last Updated : 11 Jul, 2025
The const keyword in JavaScript is a modern way to declare variables, introduced in (ES6). It is used to declare variables whose values need to remain constant throughout the lifetime of the application.
const is block-scoped, similar to let, and is useful for ensuring immutability in your code. Unlike let, the primary feature of const is that it cannot be reassigned once it has been initialized.
Syntax
const variable = value;
Variables declared with const are block-scoped, which means they are accessible only within the block, statement, or expression in which they are defined.
JavaScript
if (true) {
const x = 10;
console.log(x); // Output: 10
}
console.log(x); // ReferenceError: x is not defined
Block Scope
Variables declared with const cannot be reassigned after their initial declaration. Attempting to do so results in a TypeError.
JavaScript
const y = 20;
y = 30; // TypeError: Assignment to constant variable.
No Reassignment
Unlike let, a const variable must be initialized at the time of declaration. Declaring a const variable without assigning a value will throw a SyntaxError.
JavaScript
const z; // SyntaxError: Missing initializer in const declaration
Must Be Initialized
const makes the variable binding immutable, but if the value is an object or array, you can still modify its properties or contents.
JavaScript
const obj = { name: "Pranjal" };
obj.name = "Nanda";
console.log(obj.name);
const arr = [1, 2, 3];
arr.push(4);
console.log(arr);
Nanda [ 1, 2, 3, 4 ]
Variables declared with const cannot be redeclared within the same scope, similar to let.
JavaScript
const a = 10;
const a = 20; // SyntaxError: Identifier 'a' has already been declared
No Redeclaration
The const keyword is ideal for defining constants or variables whose values should not change during the program's execution. For example.
JavaScript
const PI = 3.14159;
const MAX_USERS = 100;
PI=10
Suitable for Constants
Using const with functions ensures that the function reference cannot be reassigned, though the function itself can still be executed normally.
JavaScript
const greet = () => console.log("Hello, world!");
greet();
greet = () => console.log("Hi!");
Safer with Functions
const aligns with modern JavaScript practices, supporting features like destructuring and modules for cleaner, maintainable code.
JavaScript
const { name, age } = { name:"Meenal", age: 28 };
console.log(name, age);
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4