As you can see, the effect of Object.preventExtensions is to prevent the adding of new properties to an object. If you are using strict mode it will throw an error, but in normal mode it will fail silently.

It is important to remember that Object.preventExtensions does not prevent manipulating the values of existing properties.

// The antarctic population drops during wintercontinentPopulations.antarctica=500;// Outputs: 500console.log(continentPopulations.antarctica);

Nor does it prevent deleting existing properties.

// In the year 2248 Antarctica was destroyed// by spacefaring dinosaurs from another dimensiondeletecontinentPopulations.antarctica;// Outputs: undefinedconsole.log(continentPopulations.antarctica);

To detect whether an object will accept new properties, use the corresponding Object.isExtensible method like so:

Object.preventExtensions and Object.isExtensible are both part of the ECMAScript 5 specification, so older browsers like IE8 don't support them. And due to the limitations of previous versions of JavaScript, these features cannot be polyfilled.

That's it for our series on JavaScript's built-in object protection methods.

Want to improve your JavaScript skills?
Subscribe to A Drip of JavaScript for biweekly tips to help you level up as a JS developer.