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.
Syntax
const myConstant = value;
Description
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.
Practical examples
Example 1
In this example, we create a constant and try to reassign a value to it.
// ONLINE-RUNNER:browser;
const myConstant = 1;
try {
myConstant = 2;
} catch (error) {
console.log(error); // TypeError: Assignment to constant variable.
}
console.log('myConstant = ' + myConstant); // 1
Output:
TypeError: Assignment to constant variable.
number = 1
Example 2
In this example, we create an uninitialized constant.
// ONLINE-RUNNER:browser;
const myConstant;
Output:
Uncaught SyntaxError: Missing initializer in const declaration
Example 3
This example shows, that constants are block-scoped.
// ONLINE-RUNNER:browser;
const myConstant = 3;
if (true) {
const myConstant = 2;
console.log(myConstant); // Output: 2
}
console.log(myConstant); // Output: 3
Output:
2
3