Constants in JavaScript
We have variables to store values in programming. Constant variable values remain the same throughout the program and cannot be changed. In compiled programming languages, a constant value is replaced at compile-time, and its use allows for other optimizations to increase the runtime efficiency of the code.
In this tutorial, we will learn about constants in JavaScript.
The keyword const
was introduced in ES6 in 2015. It is used to declare constants in JavaScript. The constant data structure is a data structure that holds information that will never change, and the variable is only declared once. A const
declaration must be initialized. Else, it will throw an error.
The declaration of the const
variable can either be global or local. The initial value for the constant is required in the same statement it is declared. In other words, we can say the const
declaration only creates a read-only value reference to the variable.
See the following example.
var a;
const b = 1;
In the above example, object a
is a variable. The object b
is a constant. Its value will remain 1 throughout the program.
It is possible to mutate constant variables. An operation that changes the value of a variable without using the assignment operator is called mutating the variable.
For example,
const age = [19, 13]
age.push(15)
console.log(age)
Output:
[19, 13, 15]