Constants (Constant)
const
is short for "constant."
A constant is something that, once assigned a value, cannot have its value changed.
Therefore, a variable declared with const
cannot be reassigned after its initial assignment.
Example:
const birthYear = 1995;
In the example above, we have assigned the value 1995 to the constant named birthYear
.
Because birthYear
is declared with const
, its value cannot be changed once it has been set.
Why use const
?
-
To store values that should not change: For instance, you can use
const
for values like the default color theme of a website or a user's date of birth, which should remain constant once set. -
Code stability: Using
const
helps prevent accidental reassignment of variables. Preventing these types of mistakes can reduce bugs in the program. -
Code readability: When you or someone else revisits the code later, the use of
const
makes it clear which values are not supposed to change, making the code easier to understand.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.