Introduction to Constants
What's a Constant?¶
-
A Constant is a value that isn't supposed to change while you are running your program. They are also known values that never change, like PI.
-
They look a lot like variables, but since they shouldn't change we call them constants.
How do we use Constants?¶
-
In earlier versions of JavaScript, um, well, we couldn't. But now in more recent versions, it is simple: just use the
const
key word rather than thelet
keyword when you want a constant. -
There is a real advantage to doing this: in most programming languages once the content of a constant is given to it, the language will not allow the program to change that content. Modern versions of JavaScript do have this mechanism as well.
-
To set up constants, we use a different naming convention and put them in a different place.
1 2 3 |
|
-
That's right we, by strong convention, name constants using ALL CAPS. And, we also assign the value to a constant right when we declare it.
-
If we have a constant name that is more than one word we use the underscore
_
to separate the words.
1 2 3 4 5 |
|
- Oh, one final thing, we need to declare constants before we declare variables.
1 2 3 4 5 6 7 8 9 |
|
New Coding Standard
Be sure to follow the naming conventions so that you as a programmer can distinguish variables from constants just by glancing at their names.
Read more¶
Related Reading
Page 20 — Now would also be a good time to read all of Chapter 2 if you haven't yet.