Preventing Object Modification in Javascript

Currently (ECMAScript 5) there are three ways to prevent or “lock down” object modification in Javascript. This is important to help prevent possible misbehaving third-party Javascript partners from tampering with your objects. Or worse - your own Javascript in other parts of your code base that you did not consider or test. Or maybe there are specific areas or parts of your code where you want to write immutable Javascript and reap the benefits?

alt text

The methods below all “inherit” the abilities of the one above it (the one at the top is the least restrictive).

At the top is Object.preventExtensions() -

  • No newly added properties

Here is an Object.preventExtensions() example:

"use strict";

var order = { Total: 100, SubTotal: 105 };

order.OrderNumber = "0001";


// TypeError: object is not extensible
order.AffiliateCode = "BAD_THIRD_PARTY_VENDOR";

Next is Object.seal() -

  • Cannot remove properties

  • Can only read/write to its properties

  • Cannot change a property’s type

  • However, you can still have an object property and modify it

Here is an Object.seal() example:

"use strict";

var order = { Total: 100, SubTotal: 105 };

order.OrderNumber = "0001";
order.Items = { Count: 0 };
order.AffiliateCode = "TRUSTED_THIRD_PARTY_VENDOR";


order.Items.Count = 2;

// TypeError: Cannot delete property
delete order.AffiliateCode;

At the bottom and most restrictive is Object.freeze() -

  • Non-writable data properties

  • Once frozen cannot become unfrozen

Here is an Object.freeze() example:

"use strict";

var order = { Total: 100, SubTotal: 105 };

order.OrderNumber = "0001";
order.AffiliateCode = "TRUSTED_THIRD_PARTY_VENDOR";


// TypeError: Cannot assign to read only property
order.Total = 500;
order.AffiliateCode = "BAD_THIRD_PARTY_VENDOR";

When Strict mode is invoked an exception is thrown when attempting to modify an object using the aforementioned methods. If use strict is not invoked then no exception is thrown and the modification attempt silently fails.

See the ECMAScript compatibility table for strict mode support.

Lead generation, eCommerce pixel partners, referral & affiliates, and commission tracking are some use cases that come to mind. What are some other scenarios to guard your Javascript objects against? And yes, unfortunately sometimes our own code can be our enemy too.