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 
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.
  1. Immutable.js: Libraries such as Immutable.js provide persistent immutable data structures. These are collections that, once created, are never changed. Any modifications to the collection return a new collection that shares as much of the structure with the original as possible, minimizing unnecessary copying.
  2. Functional Programming Techniques: Using functional programming practices such as avoiding side effects and using pure functions can help ensure immutability. By always returning new objects and never modifying input parameters, you can create a more predictable and maintainable codebase.
  3. Deep Copying: Creating deep copies of objects ensures that you're working with a completely separate copy and not a reference to the original object. Be cautious, though, as deep copying can be computationally expensive.
  4. Using TypeScript: TypeScript can allow you to define read-only properties and provide compile-time checks for immutability:
    type Point = Readonly<{
      x: number;
      y: number;
    }>
  5. Using ESLint: ESLint can help ensure immutability in JavaScript by providing linting rules that enforce certain coding practices related to immutability.
    Here are some ways ESLint can be used for this purpose:
  • Unordered List Item
  • Unordered List Item
java-script/immutability.1691423209.txt.gz · Last modified: 2023/08/07 18:46 by odefta