Course: JavaScript

Progress (0%)

  1. Foundation

  2. Numbers

  3. Strings

  4. Conditions

  5. Loops

  6. Arrays

  7. Functions

  8. Objects

  9. Exceptions

  10. HTML DOM

  11. CSSOM

  12. Events

  13. Drag and Drop

  14. opt Touch Events

  15. Misc

  16. Project: Analog Clock

JavaScript Constants

Chapter 6 12 mins

Learning outcomes:

  1. What are constants
  2. Creating constants using const
  3. Things to note about const
  4. Naming constants

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:

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

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.

Not only this, but constants allow for some pretty nice kinds of optimizations, made by the internal JavaScript engine to run the code at top speeds. How exactly these optimizations work is implementation-dependent and beyond the scope of this course.

Let's now see how to create constants in JavaScript.

Creating constants

JavaScript got the provision of constants almost two decades after its inception, with the advent of ECMAScript in 2015, via the const keyword.

The const keyword is used to define constants in JavaScript.

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

Syntactically, const is almost similar to var and let.

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 const statements.

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 const keywords, for reasons described in the previous JavaScript Variables chapter in the section: The problem with using , 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 variable.

Up next, inches is multiplied by 2.54 to get the corresponding number of centimetres. Finally, this value is output on the document using document.write().

Live Example

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 2.54 means.

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.');

Live Example

Everything is the same as before with the exception of a new constant introduced into the program, i.e. CENTIMETRES_PER_INCH.

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.

Fantastic.

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);
10
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 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;
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. 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.

In either case, we can't make any sense at all, and so it's desirable to make it a syntactic requirement to provide the initializer in a constant's definition, just as is the case in JavaScript.

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

const x = 10;

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

Moving on, do you recall what's meant by the temporal dead zone of a let variable from the previous JavaScript Variables chapter? It refers to the region prior to the variable's declaration in the source code where the variable can't be accessed.

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;
Uncaught ReferenceError: x is not defined at <anonymous>:1:13

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.