JS: Immutable objects

Immutable objects with “Object.freeze”

Common technique in JavaScript is the use of an object to hold configuration values and we can sometimes accidentally modified the value. To avoid this, we can use “Object.freeze”.

Using Object.freeze()

var artist = {
  name: "Hello Kitty",
  album: "A pretty cat"
}

// make the object immutable (cannot modify)
Object.freeze(artist);

function annouce (artist) {
  // assigning the name rather than testing equality
  if (artist.name = "Bye kitty") {
    console.log("meow meow");
  }
  else {
    console.log(artist.name);
  }
}

// output: meow meow
annouce(artist);

// output: {name: "Hello kitty", album: "A pretty cat"} <= no modification to the object
console.log(artist);

Using Ojbect.isFroze()

In ‘strict’ mode, this will throw an error. Use ‘isFroze’ to check

var artist = {
  name: "Hello kitty",
  album: "A pretty cat"
}

(function() {
  "use strict";

  // output: wink wink
  if (Ojbect.isFroze(artist)) {
    console.log("wink wink");
  }
})();

Browser compatibility

Object.freeze() - Made object immutable

Ojbect.isFroze() - Determines if an object is frozen. Return a boolean value.