EN
JavaScript - constants
0 points
In this article, we would like to show you how to declare and use constants using the const keyword in JavaScript.
xxxxxxxxxx
1
const myConstant = value;
Constants are declared using the const keyword and they must be initialized. They are block-scoped such as variables declared using the let keyword. The constant values can't be changed through reassignment, and they can't be redeclared. However, if you create a constant object or array its properties or items can be updated or removed.
In this example, we create a constant and try to reassign a value to it.
xxxxxxxxxx
1
const myConstant = 1;
2
3
try {
4
myConstant = 2;
5
} catch (error) {
6
console.log(error); // TypeError: Assignment to constant variable.
7
}
8
9
console.log('myConstant = ' + myConstant); // 1
Output:
xxxxxxxxxx
1
TypeError: Assignment to constant variable.
2
number = 1
In this example, we create an uninitialized constant.
xxxxxxxxxx
1
const myConstant;
Output:
xxxxxxxxxx
1
Uncaught SyntaxError: Missing initializer in const declaration
This example shows, that constants are block-scoped.
xxxxxxxxxx
1
const myConstant = 3;
2
3
if (true) {
4
const myConstant = 2;
5
console.log(myConstant); // Output: 2
6
}
7
8
console.log(myConstant); // Output: 3
Output:
xxxxxxxxxx
1
2
2
3