What are constants?
Where a variable acts a container of data with the ability of being change any time during the course of a program, a constant is its complete opposite.
As the name suggests:
Once a constant is defined, it stays the same forever; hence the name.
When writing programs, if we feel that we need to store a value not meant to be changed throughout the entire program, then we must create a constant to hold it. Technically, we can store it in a variable as well, but a constant makes the purpose of the value crystal clear.
When we read a piece of code containing a constant, we can immediately realize that it's meant to represent a fixed value. This surely improves the readability of the code.
constis also used in some other programming languages to denote constants. Examples include PHP, C, and C++.
const is almost similar to
Here's its syntax for defining a 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
It's mostly a matter of preference to use one or the other. We'll stick to the former, i.e. defining multiple constants with multiple
, in variable definitions.
Anyways, let's now consider a quick example.
A simple example
Suppose we want to create 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.
Based on this conversion rule, we could create such a program in seconds.
Here's the program's code:
var inches = Number(prompt('Inches?')); var centimetres = inches * 2.54; document.write(centimetres + ' centimetres.');
The call to
prompt() asks for the number of inches to convert into centimetres, which then gets converted into a number by virtue of the
Number() function. This number gets stored in the
inches is multiplied by
2.54 to get the corresponding number of centimetres. Finally, this value is output on the document using
Although the program indeed works correctly, there is a slight problem with it.
Notice the value
2.54. It's hardcoded into the program. This is the problem.
You might be able to easily tell what
2.54 means, as you've just been told to multiply centimetres by 2.54 to obtain the corresponding number of inches, but another person reading this code might not. The person might not know what exactly
After a couple of iterations of reading the code, and maybe even googling it out, one might be able to figure out that it represents the conversion rule of going from inches to centimetres, or more specifically, the number of centimetres per inch.
Ideally, however, this shouldn't have taken so long to figure out. The program should've made it extremely easy to tell that
2.54 represents the number of centimetres per inch.
The program shouldn't have buried the value
2.54 deep down into the code.
Just one such instance of burying a constant deep down into code, as was done above, won't really pose a big problem. But if there are hundreds of such instances, all scattered throughout an extremely complex program, you can imagine where we'd end up!
The solution to this problem is to simply create a constant holding the value.
In the following snippet, we rewrite the code above by storing the value
2.54 in a constant:
const CENTIMETRES_PER_INCH = 2.54; var inches = Number(prompt('Inches?')); var centimetres = inches * CENTIMETRES_PER_INCH; document.write(centimetres + ' centimetres.');
Everything is the same as before with the exception of a new constant introduced into the program, i.e.
Just by reading the name of the constant, we can immediately reason that
2.54 is the number of centimetres in an inch. (That why exactly is the name in all caps is explained in the last section below.)
And then multiplying
inches with this constant also makes more sense, i.e. we are multiplying the number of inches with the number of centimetres per inch to get the corresponding number of centimetres.
This program demonstrates a very good example of the usage of a constant.
That is, when we want to create an identifier representing a fixed value,
2.54 in this case, going with a constant is the best choice. It makes the code much more readable and maintainable in the longer run.
As stated before, 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.
Things to note
As per the definition of a constant, it's invalid to assign a value to it later on in a program after it's defined.
An example follows:
const x = 10; console.log(x); x = 20; console.log(x);
Here first we define a constant in line 1 and then log it. Following this, the constant is assigned the value
20 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;
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. If it had been possible to omit the initializer from a
const definition, then it would've meant that we'd be assigning a value to the
const later on, totally defeating the whole idea of a const, or that we'd be using an
undefined constant value, without being able to change it later on.
const x = 10; const x = '10';
Moving on, do you recall what's meant by the temporal dead zone of a
Temporal dead zones are created for
const declarations as well.
This means that we can't access a constant prior to its declaration. Doing so will lead to an error, as demonstrated below:
console.log(x); const x = 10;
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
centimetresPerInches. Which one of these seems a constant value? Well, frankly speaking, we can't figure that out!
Now consider the two identifiers
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.
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.
To restate them all, the rules are as follows:
- The name can only contain alphanumeric characters (a-z, A-Z, 0-9), underscores (
_) and dollar signs (
$); nothing else.
- The name can't begin with a digit.
- The name can't be a reserved keyword, such as