Javascript Const
The const
is a keyword used to declare a variable that cannot be reassigned.
Once a variable is declared with const
, its value cannot be changed.
As an example, let's say you declare a variable x
using const
:
const x = 10;
If you try to reassign x
, you will get an error:
x = 20; // Uncaught TypeError: Assignment to constant variable.
const
can declare both primitive
and complex values, but for complex values, properties or elements can be modified despite the variable being non-reassignable.
As an example, consider the following object:
const person = { name: 'John', age: 30 };
Even though person
cannot be reassigned, you can still modify its properties:
person.age = 40;
console.log(person); // { name: 'John', age: 40 }
const
does not make variables immutable (unable to be changed.), only their bindings to values. Thus, complex types like arrays and objects can still have their properties or elements changed.
When to use "const"?
const
should be used when a variable's value should not be reassigned. By default, const
is preferred for all variables, with let
reserved for cases where the value will change.
Using const
in JavaScript can lead to more robust and predictable code as it eliminates the possibility of accidentally changing a value, making it easier to reason about the code and helping to prevent bugs
Here are some situations where you might want to use const:
Value should not change throughout the program
When you declare a variable whose value should not change throughout the program, such as a constant value like the number of seconds in a minute or the value of Pi.
const SECONDS_IN_MINUTE = 60;
const PI = 3.14159;
Variables inside function used only once
When you declare a variable inside a function that is used only once, and its value should not be reassigned.
This can help prevent bugs that might arise from accidentally changing a value.
function exampleFunction() {
const message = "Hello, World!";
console.log(message);
}
Object or array that should not be reassigned
When you declare an object or array that should not be reassigned, but its properties or elements can be modified.
This can help prevent accidental reassignments of the entire object or array, while still allowing you to modify its properties or elements.
const person = { name: 'John', age: 30 };
person.age = 40; // Allowed