What are constants?

Where a variable is a container of data which can be changed at any time during the course of the program, a constant is its complete opposite.

As the name suggests:

A constant is a container of data that can't be changed during the course of the program.

Once a constant is defined, it stays the same forever.

When writing programs, we often come across variables that don't change throughout the entire program. Instead of creating these variables, we should rather be creating constants.

Typically constants are optimized by the internal JavaScript engine.

Even semantically, if we're reading a code containing a constant, we can immediately realize that it's meant represent a fixed value. This surely improves the readability of code.

Creating constants

In JavaScript, a constant is created using the const keyword.

const is also used in some other programming languages to denote constants. Examples include PHP, C, and C++.

Syntactically, const is similar to var with an initialization.

Here's its syntax for defining one single constant in one statement:

const name = value;

name is the name of the constant and value is its value.

Multiple constants can be defined at once by separating them with a comma (,):

const name1 = value1,
      name2 = value2,
      name3 = value3,
      nameN = valueN;

Obviously, we could also define multiple constants as separate const statements. It's merely a matter of preference as to what exactly do we use.

Anyways, let's now consider a quick example.

Suppose we have a program to convert a given value in inches to centimetres. The conversion rule is pretty basic — multiply the number of inches by 2.54 to get the corresponding number of centimetres.

The fixed value 2.54 used in the calculation is represented using the constant CENTIMETRES_PER_INCH.

Here's the program's code:


var inches = Number(prompt('Inches?'));
var centimetres = inches * CENTIMETRES_PER_INCH;

document.write(centimetres + ' centimetres.');

Live Example

This program demonstrates a very good example of the usage of a constant. That is, when we want to create an identifier representing fixed value, 2.54 in this case, going with a constant is the best choice.

It's not that using a variable in such a scenario would be wrong — it's just that, by definition, a variable is meant to hold a value with the ability to be changed later on, and hence doesn't seem to be a good choice to store a fixed value.

As per the definition of a constant, it's invalid to reassign a value to it later on in a program.

An example follows:

const x = 10;

x = 20;
Uncaught TypeError: Assignment to constant variable. at <anonymous>:4:3

Here first we define a constant in line 1 and then log it. Following this, the constant is reassigned a value in line 4. This leads to an error and likewise terminates the execution of the code.

Apart from this, a constant can't be defined without an initializer value.

Consider the code below:

const x;
x = 10;
Uncaught SyntaxError: Missing initializer in const declaration

The first statement const x is the cause of the error. Since there is no initial value assigned to the constant in line 1 as it's declared, the statement leads to an error.

This is a sensible approach. Imagine if it wasn't an error to define a constant without an initial value. That would've simply meant that it would be possible to assign a value later on to the constant. But this is against the definition of a constant i.e. it couldn't be changed later on.

Moving on, it's also impossible to redeclare a constant in JavaScript:

const x = 10;

// Redeclare x.
const x = '10';
Uncaught SyntaxError: Identifier 'x' has already been declared

Once again, this is also sensible.

Naming constants

Did you notice the naming used for the constant in the code above?

It's very conventional throughout programming to name constants using screaming snake casing. In this casing, each word is uppercased and separated from the other one using an underscore (_).

But why is the uppercasing needed?

Well, if we think about it, the uppercasing really helps us in quickly identifying constants in code and distinguishing them from ordinary variables.

Consider the two identifiers conversionRatio and centimetresPerInches. Which one of these seems a constant value? Well, frankly speaking, we can't figure that out!

Now consider the two identifiers conversionRatio and CENTIMETRES_PER_INCH. Now which one seems to be a constant? Clearly the second one.

Just by looking at the screaming casing of CENTIMETRES_PER_INCH, we were quickly able to guess that it's a constant.

The screaming snake casing convention is so common that even languages that don't have any notion whatsoever of constants, such as Python, use the casing the casing to denote constants.

Long story short: whenever naming a constant, use the screaming snake casing convention.

And conversely, whenever you come across an identifier in a program, be that in any programming language, that uses screaming snake casing, remember that the identifier is meant to represent a fixed, constant value.

Moving on, apart from the convention to use when naming constants, we have to abide by the identifier naming rules of JavaScript so that we don't end up producing syntactically invalid code.

To restate them all, the rules are as follows:

  1. The name can only contain alphanumeric characters (a-z, A-Z, 0-9), underscores (_) and dollar signs ($); nothing else.
  2. The name can't begin with a digit.
  3. The name can't be a reserved keyword, such as var, const, typeof etc.