Software programmers use various data types in their code.
A literal is a value that is expressed as itself. For example, the number 25 or the string "Hello World" are both literals.
A constant is a data type that substitutes a literal. Constants are useful in situations where
- a specific, unchanging value is to be used at various times during the software program
- you want to more easily understand the software code
A variable in a program can change its value during the course of execution of the program. A constant retains the same value throughout the program.
Comparison chart
![]() | Constant | Literal |
---|---|---|
Example | const PI = 3.14; var radius = 5; var circumference = 2 * PI * radius; | var radius = 5; var circumference = 2 * 3.14 * radius; |
Constant vs Literal Data Type - Example
Suppose we are writing a program to determine which members of a population are eligible to vote, permitted to drink, both or neither.
const DRINKING_AGE = 21; const VOTING_AGE = 18;
18
and 21
are literals. We can use these literals in all areas of our program. For example, if(age > 18)
or if(age < 21)
. But we can make our code more understandable if we use constants instead. if(age > VOTING_AGE)
is easier to understand. Other benefits of using constants are
- Constants free the programmer from having to remember what each literal should be. Often values that stay constant throughout the program have a business meaning. If there are several such values, the programmer can define them all in the beginning of the program and then work with the easier-to-remember constant names.
- If business requirements dictate that the constant be changed (for example, if the drinking age is lowered to 20 in the future), it is much easier to adapt the program. If we use literals throughout the program, the change will be hard to do and there is a good chance some instances will not be corrected.
Comments: Constant vs Literal