Constants
Constants are block-scoped variables/arrays/objects which cannot be reassigned or redeclared in the same scope (Scope is defined by the nearest curly braces). Const declaration creates a read-only reference to a value but it is not immutable.
Syntax - const nameN = valueN;
Variable scope
Constant scope can be global/local depending on the block in which it is declared. However, you cannot access constant as window object property.
e.g.
constPI = 3.14;
console.log(window.PI) //output: undefined
Mistakes to be avoided,
| No. |
Mistakes to avoid
|
Code snippet with error
|
Correct code snippet
|
Error occurred |
|
1.
|
Declaring const and not assigning value.
|
constPI;
PI = 3.14;
|
constPI = 3.14;
|
Uncaught SyntaxError: Missing initializer in const declaration.
|
|
2.
|
Reassigning const
|
constPI = 3.14;
PI = 3.14159;
|
constPI = 3.14;
|
Uncaught TypeError: Assignment to constant variable.
|
|
3.
|
Redeclaring const in same scope
|
constPI = 3.14159;
console.log("Value of PI is: "+PI);
constPI = 3.14;
|
{
constPI = 3.14159;
console.log("Value of PI is: "+PI);
}
constPI = 3.14;
|
Uncaught SyntaxError: Identifier 'PI' has already been declared.
|
|
4.
|
Reusing constant name in same scope
|
constPI = 3.14159;
console.log("Value of PI is: "+PI);
varPI = 3.14;
|
{
constPI = 3.14159;
console.log("Value of PI is: "+PI);
}
varPI = 3.14;
|
Uncaught SyntaxError: Identifier 'PI' has already been declared.
|
|
5.
|
Reusing var name in same scope
|
varPI = 3.14;
constPI = 3.14159;
|
varPI = 3.14;
{
constPI = 3.14159;
}
|
Uncaught SyntaxError: Identifier 'PI' has already been declared
|
|
6.
|
Reassigning object
|
constperson = {
name:"Honey",
weight:55
}
person = {
name:"Bunny",
weight:60
}
|
constperson = {
name:"Honey",
weight:55
}
person.name = "Bunny";
person.weight = 60;
If you want to make object immutable then use Object.freeze( person)
|
Uncaught TypeError: Assignment to constant variable.
|
|
7.
|
Changing properties of immutable const object
|
constperson = {
name:"Honey",
weight:55
}
Object.freeze(person)
person.name = "Bunny";
person.weight = 60;
|
Uncaught TypeError: Cannot assign to read only property 'name' of object '#<Object>'
|
Praneet RanePosted Sep 24, 2019, 2:59 AM
Nice Blog! Thanks