Updated April 15, 2023
Below is the syntax mentioned:
const <name of the variable> = value;
Hence to declare a constant variable, need to use the keyword ‘const’ instead of ‘let.’
const employeeName = "Karthick";
Here variable employeeName is a constant with vale ‘Karthick”.
If in case you try to change the value of employeeName to ‘Anusha,’ you will face an error as you cant reassign a constant
Only when the programmer is sure that the variable will not face any changes, then it can be declared using const to guarantee the fact that the variable is a constant
- One main thing is capitalization, which we surely help to know which are the constant values and the variables in the program.
var EMPLOYEE_AGE = 24;
- ES6 has helped people in declaring the const, which is a constant, and added new keywords ‘const’ and ‘let.’
- So you might doubt why we should capitalize when we have the keyword ‘const’ or do we need to capitalize on anything that is declared using the const keyword.
- Const creates a constant which has a read-only reference; there is no meaning that the value the variable is holding is immutable.
- Some of the constant references can change depending upon the programming logic.
- So const here only prevents users from trying to reassign the name of the variable, but the object property can be passed as objects are Pass By Reference.
- Overall, constants can be declared whether using an upper case or lower case, the most used and common convention is to all upper case letters.
Use of const keyword. Code:
Assigning or changing the value of constant EMPLOYEE_NAME in the above code.
You can see the error on the screenshot as ‘Assignment to the constant variable online 3.’
Redeclaring the constant and reassigning the value.
Constant EMPLOYEE_NAME has already been declared, which is a Syntax error
Not initializing the constant.
We are just declaring the constant EMPLOYEE_AGE and not initializing it with a value. Hence the Missing Initializer Syntax error.
Commented lines, you people can just try out by uncommenting it. It will give an error as ‘error: Uncaught TypeError: Assignment to constant variable.’
One of the interesting parts of using constants is to know about the Object.freeze() method.
If you want any of the objects to be immutable, we need to use Object.freeze() method, so by freezing the object properties of the object are frozen but not the Object references by the properties. Let us take an example,
Using Object.freeze() method for const.
SCHOOL Object is const and frozen; no other details will be mutable, but the SCHOOL.studentAddress Object can be mutable, new properties can be added.