JavaScript const Keyword Explained with Examples

Hi friends! Today, I will teach you how the const keyword works in JavaScript works and when you should use it.

The const keyword is used to declare a variable that can’t be changed after its declaration. This keyword is short for constant (which means “doesn’t change”), and it’s used in a similar manner to the let and var keywords.

You write the keyword, followed it up with a variable name, the assignment = operator, and the variable’s value:

// a const variable declaration
const message = 'Hello!';

We’ll see how the const keyword differs from the let keyword next. Let’s write a variable called name that has a string value, and we change the value after the declaration:

let message = 'Hello!';
message = 'Good morning!';
console.log(message); // Good morning!

The code runs without any problem, and the console.log displays the new value ‘Good morning!’ instead of the first value ‘Hello!’.

Now let’s replace let with const and run the code again:

const message = 'Hello!';
message = 'Good morning!';
console.log(message);

This time, we get an error as follows:

TypeError: Assignment to constant variable.

Since we declared the message variable as a constant, JavaScript responded with an error when we tried to assign a new value to the variable.

A constant variable is usually written in an all-uppercase format (message becomes MESSAGE)

If the variable name is more than one word, separate the words using underscores. For example: TOTAL_MESSAGE_COUNT.

The const Keyword Only Prevents Reassignment

The const keyword doesn’t allow you to change the object the variable points to, but you can still change the data in the object.

For example, suppose you have a person object that has a name property. You can change the name property value even when you declare the object using a const as follows:

const person = {
  name: 'Jackson'
};

person.name = 'Nathan';  // ✅ this doesn't cause an error

console.log(person.name); // Nathan

But if you try to change the object the variable points to, you’ll get the same error:

const person = {
  name: 'Jackson'
};

person = {
  name: 'Nathan'
};  // ❌ error!

Note carefully the differences between the two examples above. In the first example, the name property is modified, but the variable person still points to the same object. This is allowed.

In the second example, we tried to change the object the person variable points to, and this is not allowed.

The same goes when you have a variable pointing to an array. You can change the elements stored in the array, but not the array itself.

The const keyword prevents reassignment (making the variable point to a different value) but not mutation (editing the value itself)

When to use the const keyword

Now that you know how the const keyword works, when do you need to use it in your code?

The answer is when you need to declare a variable that will never change during the lifecycle of your program.

For example, suppose you’re writing a program that has a lot of time calculations. You can declare a few constants that store the relation between hours, minutes, and seconds as follows:

// dealing with time units
const SECONDS_IN_MINUTE = 60;
const SECONDS_IN_HOUR = 3600;
const HOURS_IN_DAY = 24;

// date units (days, weeks, months, years)
const DAYS_IN_WEEK = 7;
const WEEKS_IN_MONTH = 4;
const MONTHS_IN_YEAR = 12;

There will always be 60 seconds in a minute, 3600 seconds in a minute, and 24 hours in a day, no matter where you live, as long as it’s on Earth 😄

You also always have 7 days in a week, 4 weeks in a month, and 12 months in a year. A month can have different days (27, 28, 30, 31) so don’t make it a constant.

Another example is when you need to work with geometry. To calculate the circumference of a circle, you need the PI value, which is a constant:

const PI = 3.14159265359;
let radius = 7;
let circumference = 2 * PI * radius;

console.log(circumference); // 43.98229715026

I hope these examples help you get the point. The key to knowing when to use const is to ask yourself this: would you have to assign a new value to the variable later, after its declaration? If not, use const. Otherwise, use let.

Conclusion

This article has shown you how the const keyword works, how it doesn’t prevent mutation, and when to use it in your project.

The const keyword is kind of bewildering in how it doesn’t prevent mutation. Indeed, JavaScript is a tricky language with some weird behaviors that can lead to errors.

I have some more articles related to JavaScript that you can read here:

Bubble Sort in JavaScript
Understanding Encapsulation in JavaScript

I also have a JavaScript course that’s currently in progress. I want to make this course the best and complete JavaScript course for beginners. If you enjoy this article, you might want to check it out.

Thanks for reading. See you next time! 👋

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.