The preventExtensions()
method in JavaScript is a crucial function when you prefer to lock down an object, preventing the addition of new properties. This technique is valuable in scenarios where you need to ensure the integrity and structure of an object once it has been created, making the object immutable in terms of its properties.
In this article, you will learn how to employ preventExtensions()
in your JavaScript code. Discover how this method can secure objects by making them non-extensible and explore different scenarios where this can be particularly useful, such as in configuration objects or when sealing an object's structure after its initial creation.
preventExtensions()
preventExtensions()
Start by creating an object.
Apply the preventExtensions()
method to this object.
const car = { brand: 'Toyota', model: 'Corolla' };
Object.preventExtensions(car);
This code snippet creates an object car
and ensures no new properties can be added to it.
Check whether an object is still extensible using Object.isExtensible()
.
const isExtensible = Object.isExtensible(car);
console.log(isExtensible); // Outputs: false
After applying preventExtensions()
, checking the object with Object.isExtensible()
returns false
, confirming that you cannot add new properties.
Try to add a new property to a non-extensible object and see the outcome.
car.color = 'Black';
console.log(car.color); // Outputs: undefined
Since preventExtensions()
was called on the car
object, attempting to add a new property color
results in no changes.
Be aware of silent failures in non-strict mode and errors in strict mode.
If you work in strict mode and attempt to add a property to a non-extensible object, JavaScript throws a TypeError:
'use strict';
try {
car.year = 2021;
} catch (e) {
console.log(e.message); // Outputs: Cannot add property year, object is not extensible
}
This code example demonstrates that in strict mode, JavaScript actively prevents the addition of new properties by throwing appropriate errors.
Using the preventExtensions()
method in JavaScript effectively locks down an object, preventing any new properties from being added. This action is particularly useful when maintaining the integrity of objects in large projects, or when the structure of the object should not change partway through execution. Understand how preventExtensions()
interacts with code in both strict and non-strict modes to fully harness its potential in safeguarding object structures. By mastering the techniques discussed, you ensure enhanced control and stability in your JavaScript applications.