Lesson 5. Declaring constants with const

 

After reading lesson 5, you will

  • Understand what constants are and how they work.
  • Know when to use constants.

The keyword const stands for constant, as in never changing. Many programs have values that never change, whether by intention or by happenstance. Values declared with const, referred to as constants, have the same characteristics as those declared with let, which you learned about in the previous chapter, with the additional feature of reassignment being forbidden.

Consider this

Consider the following switch statement, which uses flags to determine what type of action is being performed. The uppercasing of ADD_ITEM and DEL_ITEM indicates that these are values that are never expected to change,[a] but what would happen if they did change? How would that affect the behavior of the program? How could you author the application to protect from that?

aThis uppercasing is purely by convention and not a required syntax.

switch (action.type) {
  case ADD_ITEM:
    // handle adding a new item
  break;
  case DEL_ITEM:
    // handle deleting an item
  break;
};

5.1. How constants work

Constants cannot be reassigned. This means that once you assign the value of a constant, any attempt to assign a new value will result in an error:

const myConst = 5;

myConst = 6;            1
!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":2,\"ch\":24},{\"line\":2,\"ch\":25}]]"}
!@%STYLE%@!
  • 1 Error

5.2. When to use constants

Summary