How to Update a const Object in JavaScript

avatar

Borislav Hadzhiev

Last updated: Nov 20, 2021

banner

Photo from Unsplash

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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.