Constant Declaration Keyword, const
const
is short for Constant
, which means that once a value has been set, it cannot be changed.
Therefore, a variable declared using const
cannot have its value altered once it is assigned.
const birthYear = 1995;
In the example above, the constant birthYear
is assigned the numeric value 1995.
Since birthYear
is declared with const
, its value cannot be changed once set.
The scope of a const
declared variable, like let
, is block-level scope
.
Thus, a variable declared with const
inside curly braces is not accessible outside that code block.
Why Use const as a Constant Variable?
-
To Store Values That Should Not Change: It is used when you want to safely store values that should not change once set, such as a website's default color or a user's birth year.
-
Improving Code Stability: By using
const
, you prevent the value from being accidentally modified. This helps to reduce errors in your program, making it more robust.
A constant declared with const
can have its value changed.
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result