Object.freeze: Immutable Objects

By  on  

One of my favorite part of JavaScript has always been mutability of objects.  I loved that MooTools and likewise frameworks could modify native prototypes to enhance them with functionality we knew the language need; in fact, I credit MooTools with pushing the web forward.

There are cases, however, where you don't want an object to be modifiable; you don't want values for existing properties to be changed, added, or removed.  That's where Object.freeze can help -- with Object.freeze you can create immutable objects you can trust!

const obj = Object.freeze({
    x: 1,
    y: 2
});

// None of these do anything
obj.x = 8; // { x: 1, y: 2}
delete obj.x; // { x: 1, y: 2}
obj.z = 3;  // { x: 1, y: 2}

Object.freeze is a welcomed addition to JavaScript and a necessary one.  If you have objects whose integrity you want to secure, immutability is required.  Object.seal provides similar functionality without the ability to freeze values, so Object.freeze is your best choice when you want to lock down an object!

Recent Features

  • By
    CSS Animations Between Media Queries

    CSS animations are right up there with sliced bread. CSS animations are efficient because they can be hardware accelerated, they require no JavaScript overhead, and they are composed of very little CSS code. Quite often we add CSS transforms to elements via CSS during...

  • By
    I’m an Impostor

    This is the hardest thing I've ever had to write, much less admit to myself.  I've written resignation letters from jobs I've loved, I've ended relationships, I've failed at a host of tasks, and let myself down in my life.  All of those feelings were very...

Incredible Demos

  • By
    Add Styles to Console Statements

    I was recently checking out Google Plus because they implement some awesome effects.  I opened the console and same the following message: WARNING! Using this console may allow attackers to impersonate you and steal your information using an attack called Self-XSS. Do not enter or paste code that you...

  • By
    Table Cell and Position Absolute

    If you follow me on Twitter, you saw me rage about trying to make position: absolute work within a TD element or display: table-cell element.  Chrome?  Check.  Internet Explorer?  Check.  Firefox?  Ugh, FML.  I tinkered in the console...and cussed.  I did some researched...and I...

Discussion

  1. Shallow

    It’s good to remind that Object.freeze does only shallow freeze.

  2. That’s a nice feature. Much needed. However, I hope the browser support is good.

  3. MaxArt

    Should I remind that MooTools’ practice to extend native prototypes prevented W3C to use well-known names like contains and flatten, because it would have literally broken the web?
    Extending native prototypes is the last thing you’d want in a general purpose library.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!