How to Declare Constants in JavaScript?
Read this tutorial and learn useful information about declaring a constant by using the const keyword which creates a read-only reference to the value.
The const Variable
ES2015 introduced two new JavaScript keywords: <kbd class="highlighted">let</kbd> and <kbd class="highlighted">const</kbd>. Variables defined with const behave like let variables, except they cannot be re-assigned. In programming, a constant is something that does not change. The <kbd class="highlighted">const</kbd> keyword creates a read-only reference to a value, which does not mean the value it holds is immutable. It only indicates that the variable identifier cannot be re-assigned.
ES6 provides a new way of declaring a constant by using the const keyword which creates a read-only reference to a value:
Javascript const keyword
const CONSTANT_VALUE = "someValue";This works in almost all browsers.
Capitalization indicates that some values should be constant.
Local variables with block scope can be declared with const. Assume we have a constant variable CONSTANT_VALUE. After declaring a value as a constant, you cannot assign a new value to it:
Javascript const keyword
Javascript const keyword
Javascript const keyword
A constant cannot be changed through re-assignment, and it cannot be re-declared. However, const can be changed if it is an object because when you're adding to an array or object you're not re-assigning or re-declaring the constant; it's already declared and assigned, you're just modifying the "list" that the constant points to. So this works fine:
Javascript const keyword for objects
Javascript const keyword for array