JavaScript Constants

In this article, you’ll learn about JavaScript constants that were introduced in ES6.

So before ES6 you could only declare variables in JavaScript using the var keyword.

var myVariable = 'Hello';

Truth be told, you don’t even really need the var keyword but it helped to indicate this is the first use of that particular variable name.

With the advent of ES6 there came a new way to declare variables, using the const keyword.

const myVariable = 'Hello';

So what’s the difference? Well, apart from the scoping of the variable, a variable declared with the const keyword cannot be changed after the fact. In other words, once you’ve assigned a value to a constant variable you can’t assign any other values to the same variable name.

const myVariable = 'Hello';
myVariable = 'World'; // TypeError: Assignment to constant variable.

This means constant variables are protected - you can’t accidentally assign a value - ensuring your code is more predictable.

When should you use constant variables?

The short answer is, whenever you can really. If, anywhere in your code, you don’t re-assign values to a variable then set it to a constant. In fact, some linters will complain if you don’t use const when there is no re-assignment to a particular variable.

Learn about JavaScript constants on the Junior Developer Central YouTube Channel.