User Tools

Site Tools


java-script:immutability

This is an old revision of the document!


Ensuring immutability in Java Script

Ensuring immutability in JavaScript means creating objects and values that cannot be changed once they are created.
While JavaScript does not have built-in support for immutability in the way that some other languages do, there are several practices and libraries that you can use to achieve this goal:

  1. Using const for Variables: Declaring variables with const ensures that the variable itself cannot be reassigned, but if the variable is an object or an array, its contents can still be changed:
    const a = [1, 2, 3];
    a.push(4); // This will work because the array itself is mutable.
    a = [4, 5, 6]; // This will cause an error because `a` cannot be reassigned.
  2. Object.freeze: You can use Object.freeze() to make an object immutable. It prevents new properties from being added to the object, existing properties from being removed, and it prevents changing the enumerability, configurability, and writability of existing properties:
    const obj = { x: 5, y: 6 };
    Object.freeze(obj);
    obj.x = 10; // Will have no effect

    <note>Please note that Object.freeze() is shallow, meaning that it only affects the immediate properties of the object. If the object contains other objects, those objects will not be frozen.</note>

  3. Ordered List Item
java-script/immutability.1691422647.txt.gz · Last modified: 2023/08/07 18:37 by odefta