You can define a const variable using the const keyword in JavaScript. In the same way, you declare variables with let and var.
const var_name= value;
The value of a constant can’t be changed through reassignment (i.e. by using the assignment operator), has Block Scope and it can’t be redeclared.
Note: JavaScript const variables must be assigned a value when they are declared:
JavaScript const variable
Simple example code variables cannot be reassigned.
<!DOCTYPE html>
<html>
<body>
<script>
const PI = 300;
try{
PI = 3.14;
PI = PI + 10;
}catch(error){
console.log(error)
}
console.log(PI)
</script>
</body>
</html>
Output:
Const variable cannot be hoisted
<script>
x = 100;
document.write(x);
const x; //Syntax Error
</script>
const variable cannot be initialized after the declaration
<script>
const x;
x = 100; //Syntax Error
document.write(x);
</script>
Block scope
if (MY_FAV === 7) {
// this is fine and creates a block scoped MY_FAV variable
// (works equally well with let to declare a block scoped non const variable)
let MY_FAV = 20;
// MY_FAV is now 20
console.log('my favorite number is ' + MY_FAV);
// this gets hoisted into the global context and throws an error
var MY_FAV = 20;
}
// MY_FAV is still 7
console.log('my favorite number is ' + MY_FAV);
It’s good practice to use const
for values that shouldn’t be reassigned, as it can help prevent accidental reassignments and make your code more robust. However, it’s important to note that const
does not make objects or arrays immutable. If you need immutability, you may need to use other techniques, such as the Object.freeze()
method for objects or using immutable data structures.
Comment if you have any doubts or suggestions on this JS const topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version