JavaScript const
The const keyword has all the properties that are the same as the let keyword, except the user cannot update it and have to assign it with a value at the time of declaration. These variables also have the block scope. It is mainly used to create constant variables whose values can not be changed once they are initialized with a value.
Example 1: This code tries to change the value of the const variable.
const a = 10;
function f() {
a = 9
console.log(a)
}
f();
Output:
TypeError:Assignment to constant variable.
Example 2: This code explains the use of the const keyword to declare the JavaScript objects.
const a = {
prop1: 10,
prop2: 9
}
// It is allowed
a.prop1 = 3
// It is not allowed
a = {
b: 10,
prop2: 9
}
Output:
Uncaught SyntaxError: Unexpected identifier
Difference between var, let and const keywords in JavaScript
The keywords var, let, and const in JavaScript define the variable scope and behavior. The var keyword has function scope and is hoisted. The let and const keywords have block scope, with const requiring an initial value and preventing reassignment.