DEV Community


Declaring a Read-Only Variable with the const Keyword

rthefounding profile image Randy Rivera ・1 min read
  • The keyword let is not the only way to declare variables. In ES6, you can also declare variables using the const keyword. Variables declared using const are read-only. They are a constant value, which means that once a variable is assigned with const, it cannot be reassigned.
  • Ex:
const FAV_SYSTEM = "PS5";
FAV_SYSTEM = "Xbox";
Enter fullscreen mode Exit fullscreen mode
  • The console will display an error due to reassigning the value of FAV_PET. As you can see, trying to reassign a variable declared with const will throw an error. You should always name variables you don't want to reassign using the const keyword. This actually does help when you accidentally reassign a variable that is meant to stay constant. A good way when naming constants is to use all uppercase letters, with words separated by an underscore.
  • Note: Use uppercase variable identifiers for immutable values and lowercase or camelCase for mutable values (objects and arrays).

Discussion (0)

Forem Open with the Forem app