Posts tagged with immutability

Immutable Javascript

November 20th, 2011

Something I quickly whipped up the other day, which you can find on GitHub as a Gist.

Wish you had some immutability in Javascript? Now you can!

var t = {a: 1, b: 2}.immutable();
console.log(t.a, t.b);
try {
  t.a = 3; // ->  Uncaught Error: a is immutable and cannot be modified.
} catch (e) {
  console.log(e);
}
var t2 = t.copy({a: 3});
console.log(t2.a, t2.b);
t2.mutable();
t2.a = 1;
console.log(t2.a, t2.b);

As you can see, the methods immutable, copy, and mutable are added to Object.prototype. This is done using custom getters and setters to mask the original properties, so it only works with objects that expose them and not things like strings. Of course, if you figure out how to get this to work for other Javascript datatypes, please let me know!

Javascript Primitives

February 13th, 2010

From the Mozilla Javascript Glossary:

primitive, primitive value
A data that is not an object and does not have any methods. JavaScript has 5 primitive datatypes: string, number, boolean, null, undefined. With the exception of null and undefined, all primitives values have object equivalents which wrap around the primitive values, e.g. a String object wraps around a string primitive. All primitives are immutable.

Did you know that all Javascript primatives are immutable? I sure didn’t.