Borislav Hadzhiev
Sat Nov 20 2021·1 min read
Photo by Robson Morgan
Use dot or bracket notation to update the values of an object that was
declared using the const
keyword, e.g. obj.name = 'New Value'
. The key-value
pairs of an object declared using const
can be updated directly, but the
variable cannot be reassigned.
const obj = { name: 'Tom', age: 30, }; // ✅ works obj.name = 'John'; obj.age = 29; console.log(obj); // 👉️ {name: 'John', age: 29} // ⛔️ doesn't work // ❌️ Error: Assignment to constant variable. obj = {name: 'John', age: 29};
When a variable is declared using the const keyword, the variable cannot be reassigned, however if the variable is an object or array, its values can directly be updated.
// ✅ works const obj = {country: 'Chile'}; obj['country'] = 'Columbia'; console.log(obj); // 👉️ {country: 'Columbia'} const example = 'hello'; // ⛔️ Error: Assignment to constant variable. example = 'test';
If you're looking to create an object whose values cannot be updated, you have to use the Object.freeze method.
const obj = {country: 'Chile'}; Object.freeze(obj); obj.country = 'Columbia'; console.log(obj); // 👉️ {country: 'Chile'}
Because we used the const
keyword to declare the object, the variable cannot
be reassigned.
The Object.freeze
method freezes the object:
const
keyword and the Object.freeze
method, makes the object immutable.In closing, declaring a variable using the const
keyword means that the
variable cannot be reassigned, it doesn't make the value stored in the variable
immutable.