Making an unmodifiable object in Javascript
2 min read

Making an unmodifiable object in Javascript

Making an unmodifiable object in Javascript

Let's say you have a Javascript object, maybe a dictionary or an array and you want to prevent the users from modifying it.

var permissions_arr = ['can', 'not', 'modify'];
var permissions_obj = {
    can: true
};

In this case, Object.freeze is your friend! Supported even by Internet Explorer (9 and above, but still...), it freezes an object, preventing the additionm deletion or change of the existent properties. So if you do this:

var permissions_arr = ['can', 'not', 'modify'];
var permissions_obj = {
    can: true
};

Object.freeze(permissions_arr);
Object.freeze(permissions_obj);

From now on, you will no longer be able to change these objects. You either run into a straigh error, or your attempts actually have no effect on them.

object_freeze

However, there is a catch. You can simply redeclare them, therefore bypassing the security measures put in place by Object.freeze.

redeclaring-frozen-objects

In this scenario, all you have to do is redeclare them as constants, instead of variables.

const permissions_arr = ['can', 'not', 'modify'];
const permissions_obj = {
    can: true
};

Object.freeze(permissions_arr);
Object.freeze(permissions_obj);

Now they are trully immutable!

const-frozen-objects

What if you cannot declare them as constants? For example, what if they were window properties, because you need them to be global?

window.permissions_arr = ['can', 'not', 'modify'];
window.permissions_obj = {
    can: true
};

This stackoverflow answer offers a solution for our new predicament, in form of the Object.defineProperty method. Now if you do this:

window.permissions_arr = ['can', 'not', 'modify'];
window.permissions_obj = {
    can: true
};

Object.defineProperty(window, "permissions_arr", { configurable: false, writable: false });
Object.defineProperty(window, "permissions_obj", { configurable: false, writable: false });

And now you're golden!

frozen-properties

Armed with these metods, now everyone can make something in Javascript that others cannot modify. Egoism at its finest!