In ECMAScript 6 (ES6), the keyword that allows for declaring read-only named constants is const
. Unlike var
and let
which declare variables, const
is used to declare a constant - a value that, once declared, cannot be changed.
To understand how const
works, let's look at some examples. Here's how you would typically use const
:
const PI = 3.14159;
In this example, PI is a constant that holds the value of pi to 5 decimal places. Once declared, the value of PI cannot be changed. So, if you try to reassign a value to PI:
PI = 3.14; // This will throw an error
The JavaScript engine will throw an error because you’re trying to change a read-only constant.
let
, var
and const
Understanding the difference between let
, var
, and const
is vital in JavaScript programming.
var
: Prior to ES6, developers could only use var
to declare variables. var
is function-scoped, which means if a variable is declared within a function using var
, it can't be accessed outside that function.
let
: Introduced in ES6, let
allows developers to declare block-scoped variables. They can be updated but not re-declared.
const
: Also introduced in ES6, const
is similar to let
but is read-only. Once the value is set, it cannot be changed.
While var
, let
, and const
all have their uses, best practices suggest using let
and const
as much as possible and limiting the use of var
. Because let
and const
are block-scoped, they help to prevent bugs that arise from the function-scoped nature of var
.
The const
keyword in ES6 allows programmers to declare read-only constants, providing a way to define a value that shouldn’t be changed. However, remember to use these ES6 features wisely and according to the best practices in your JavaScript programs.