Variables store data with the ability to be changed. Constants store data with no ability to be changed.
As the name implies, constants are used in programming to store constant values that won't ever be changed in a program. Just like variables they can also contain data of any type - strings, numbers, booleans etc and follow the same naming rules.
Constants are containers for holding data that can't be changed during the execution of the program.
Creating constants - const keyword
Constants in JavaScript can be created using the
But unlike variables, constants have to be initialised as soon as they are created. The following would throw an error which is pretty clear in what it says.
And just like we said constants can't be changed.
And that's it for constants! Easy, aren't they?
const
keyword.
const num = 10;
const txt = "Hello!";
const num; // Uncaught SyntaxError: Missing initializer in const declaration
num = 10;
And just like we said constants can't be changed.
const num = 10;
num = 5; // can't change this constant