Skip to content

Try our new Crash Courses!

Buy one of our new Crash Courses, now hosted on Teachable.

Constants – JavaScript

Summary

To create a constant in JavaScript, use the const keyword:

const myConstant = 0;

Details

A constant in JavaScript allows you to store a value. Once the value has been set the first time, it can’t be changed later on in your code.

const myConstant = 0;
myConstant = 1; // This will generate an error

A constant is created using the const keyword. A value is assigned to the constant using the equals sign.

You can use constants to hold many different types of values: strings, numbers, booleans, arrays, objects, etc.

Naming convention

In JavaScript, variable and constant names are written using camelCase. If a constant name is just a single word, the name is written in lowercase letters, like this:

const name = 'John Smith';

If a constant name is composed of multiple words, then the first word is written in lowercase letters while the first letter of each subsequent word is capitalized, like this:

const myFirstName = 'John';

Demo

Exercises

Try the following statements in the console:

const myConstant = 10
myConstant = 11

The second line will generate an error since you can’t change the value of a constant.

References

JavaScript constants on MDN

Back to: JavaScript Reference > JS Basic Syntax