JavaScript(JS) const
const
is a keyword in JavaScript introduced in ES6 (ECMAScript 2015) that is used to declare a constant variable that cannot be reassigned.
Declaring a variable with const
creates a read-only reference to a value that cannot be changed. This means that once a variable is assigned a value using const
, it cannot be reassigned to a different value.
Here's an example of using const
to declare a constant variable:
const PI = 3.14159;
In this example, PI
is declared as a constant variable and assigned the value of 3.14159
. Once PI
is assigned a value using const
, it cannot be reassigned to a different value.
While const
variables cannot be reassigned, their contents can still be modified if they are objects or arrays. For example, you can modify the contents of an array or object that is assigned to a const
variable, but you cannot reassign the variable to a different array or object.
Using const
can help prevent errors caused by accidental reassignment of variables and make it easier to reason about the code by clearly defining the values that should not be changed.