Protecting Objects In JavaScript

19 / Sep / 2013 by Sahil Chitkara 0 comments

JavaScript is an amazing language. Its like a Lego constructor, depending on different parts you join together, you may get the script you need or just a pile of unwanted codes. Information hiding gets very important when you want to give access to only minimal interface of a module. Depending on the level of protection, this blog discusses each and every level with live examples on NodeJS console, allowing you to check them live and make changes in existing code to see how a change will happen if you insert a few lines of your own code.

Based on level of protection, it can be distinguished in three types:

1. Preventing Extensions:

[js]Object.preventExtentions(" Your Object name ");
Object.isExtensible(" Your object name ");
// it will return Boolean value (true/false)[/js]

After  this, it is impossible to add new properties to your prevented object. But one is still able to delete properties of an object. Lets take an Example

[js]var record={id:24,author:"sahil"};

// now we add a new property to Object record



// it will print "undefined"[/js]

You can still delete properties in above example


//result: true;

//result: undefined[/js]

You can also see the example live on NodeJS Console:

2. Sealing

[js]Object.seal(" Your Object Name");
//return boolean value true/false[/js]

Sealing of an object doesn’t allow that object to extend (Prevent Extensions) and  also make its properties non-configurable.To check property description for a particular property we can do it by “getOwnPropertyDescriptor”. Example:




Though we can still change the property ‘id’:


but the changes to attributes cannot be made:


Result: cannot redefine property ‘id’

Example live on NodeJS Console:

3. Freezing

[js]Objects.freeze(" your object name ");[/js]

Freezing is strongest among all and freezing contains all features of both ‘prevent extensions’ as  well as ‘sealing’. After freezing, creation ,deletion and updation of new property/properties is/are not possible .

[js]var record={id:17,author:"sahil"};



// it will print 17[/js]

Checking whether object is frozen

[js]Object.freeze(" your object name ");[/js]

To see it live, visit:


Leave a Reply

Your email address will not be published. Required fields are marked *