Skip to content

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 the let 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
// Declaring Constants
const INCREMENT_VALUE = 1;
const INITIAL_VALUE = 0;
  • 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
// Constants with multi-word names
// Declare Constants
const SALES_TAX = 0.5;
const MAXIMUM_VALUE = 1000;
const BYE_MESSAGE = "Good bye, have a nice day";
  • Oh, one final thing, we need to declare constants before we declare variables.
1
2
3
4
5
6
7
8
9
// Declaring constants and variables
// Declare Constants
const PI = 3.14159265358979323846264;
const LARGEST_OPTION = 1000000;

// Declare Variables
let firstName;
let enteredNumber;
let outputElement;

New Coding Standard

Constants

Be sure to follow the naming conventions so that you as a programmer can distinguish variables from constants just by glancing at their names.