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
    6 Things You Didn’t Know About Firefox OS

    Firefox OS is all over the tech news and for good reason:  Mozilla's finally given web developers the platform that they need to create apps the way they've been creating them for years -- with CSS, HTML, and JavaScript.  Firefox OS has been rapidly improving...

  • By
    fetch API

    One of the worst kept secrets about AJAX on the web is that the underlying API for it, XMLHttpRequest, wasn't really made for what we've been using it for.  We've done well to create elegant APIs around XHR but we know we can do better.  Our effort to...

Incredible Demos

  • By
    Retrieve Your Gmail Emails Using PHP and IMAP

    Grabbing emails from your Gmail account using PHP is probably easier than you think. Armed with PHP and its IMAP extension, you can retrieve emails from your Gmail account in no time! Just for fun, I'll be using the MooTools Fx.Accordion plugin...

  • By
    Introducing MooTools LazyLoad

    Once concept I'm very fond of is lazy loading. Lazy loading defers the loading of resources (usually images) until they are needed. Why load stuff you never need if you can prevent it, right? I've created LazyLoad, a customizable MooTools plugin that...

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!