Skip to content

JavaScript immutable object | Code

  • by

JavaScript immutable objects are objects whose state cannot be changed once the object is created.

Object.freeze(obj)

You can freeze an object that no one can change. You can not add/remove properties or modify property values. The frozen object is no longer extensible.

  • Use Object.freeze(obj) to freeze an object.
  • Use Object.isFrozen(obj) to know if the object is frozen.

JavaScript immutable object

Simple example code.

<!DOCTYPE html>
<html lang="en">
<body>
  <script>
   const obj = {
    prop: 100,
    foo: 'bar' };

    Object.freeze(obj);

    obj.prop = 200;

    console.log(obj);

  </script>
</body>
</html>

Output:

JavaScript immutable object

What difference between a frozen object and an object declared with the const keyword?

Answer: The const keyword and Object.freeze() are not the same things. If an object is created with the const keyword then you can not reassign another value. However, you can modify the assigned objects in whatever way you want.

But if you try to assign a new object to the supportedLanguages variable. You will get this error:

<script>
   const supportedLanguages = {
    'af': 'Afrikaans',
    'bn': 'Bengali',
    'de': 'German',
    'en': 'English',
    'fr': 'French'
  }
    // Add a new property
    supportedLanguages['kn'] = 'Kannada';

    // Modify an existing property
    supportedLanguages["af"] = 'something else';

    // Delete a property
    delete supportedLanguages.bn; // returns true

    // log the object to the console
    console.log(supportedLanguages);
    supportedLanguages = {'id': 'Indonesian'};
  </script>

Output:

Object { af: "something else", de: "German", en: "English", fr: "French", kn: "Kannada" }
Uncaught TypeError: invalid assignment to const 'supportedLanguages'

Do comment if you have any doubts or suggestions on this Js immutable topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading