How to Update a Const Object in JavaScript

avatar

Borislav Hadzhiev

Sat Nov 20 20211 min read

banner

Photo by Robson Morgan

Update a Const Object in JavaScript #

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.

index.js
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.

index.js
// โœ… 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.

index.js
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:

  • preventing the key-value pairs to be changed
  • new properties to be added
  • existing properties to be deleted
The combination of using the 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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee