The JavaScript const keyword is used to define a new variable. Use it when you do not want to change the value of that variable for the whole program.
const varName = value;
A normal variable value can be changed but const variable values can’t be changed. You don’t have to use var
or let
keyword while using the const
keyword.
Key points about const
:
An assignment is required at declaration: You must assign a value to a const
variable at the time of declaration. Unlike let
or var
, you cannot declare a const
variable without initializing it.
const x; // SyntaxError: Missing initializer in const declaration
Block-scoped: Like let
, const
is block-scoped. It means that the scope of a const
variable is limited to the block (enclosed by curly braces) in which it is defined.
if (true) {
const y = 10;
}
// console.log(y); // ReferenceError: y is not defined
Immutable values, not variables: While the variable itself cannot be reassigned, it’s important to understand that its value may not be immutable. For example, if a const
variable holds an object or an array, properties or elements of that object or array can still be changed.
const person = { name: 'John' };
person.name = 'Jane'; // Valid, because the object itself is not immutable
Function-scoped in strict mode: In ECMAScript 6 (ES6) and later, const
and let
are block-scoped. However, when used in ECMAScript 5 (ES5) strict mode, const
is function-scoped.
'use strict';
if (true) {
const z = 42;
}
// console.log(z); // ReferenceError: z is not defined
JavaScript const example
A simple example code const variable can’t be reassigned.
<!DOCTYPE html>
<html>
<body>
<script>
const number = 100;
try {
number = 99;
} catch (err) {
console.log(err);
}
console.log(number);
</script>
</body>
</html>
Output:
You can change the elements of a constant array by an index value.
const cars = ["A", "B", "C"];
// You can change an element:
cars[0] = "X";
// You can add an element:
cars.push("Y");
But you can NOT reassign the array:
<script>
const cars = ["A", "B", "C"];
cars = ["X", "Y", "Z"]; // Uncaught TypeError: invalid assignment to const ‘cars’
</script>
Same with constant Objects, You can change the properties of a constant object but can’t reassign the object:
Where to use JavaScript const?
Answer: Anytime you can declare a variable with const
unless you know that the value will change. You use it with:-
- A new Array
- A new Object
- A new Function
- A new RegExp
Comment if you have any doubts or suggestions on this JS const topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version