What is `Object.preventExtensions()` for?
Topics
JavaScript
Edit on GitHub
TL;DR
Object.preventExtensions()
is a method in JavaScript that prevents new properties from being added to an object. However, it does not affect the deletion or modification of existing properties. This method is useful when you want to ensure that an object remains in a certain shape and no additional properties can be added to it.
What is Object.preventExtensions()
for?
Object.preventExtensions()
is a method in JavaScript that is used to prevent new properties from being added to an object. This method is part of the ECMAScript 5 specification and is useful for maintaining the integrity of an object by ensuring that its structure cannot be altered by adding new properties.
Syntax
obj
: The object which should be made non-extensible.
Behavior
- Once an object is made non-extensible, you cannot add new properties to it.
- Existing properties can still be modified or deleted.
- The method returns the object that was passed to it.
Example
Checking if an object is extensible
You can check if an object is extensible using the Object.isExtensible()
method.
Use cases
- Immutable object structure: When you want to ensure that the structure of an object remains unchanged, you can use
Object.preventExtensions()
. - Security: Preventing extensions can be useful in scenarios where you want to avoid accidental or malicious addition of properties to an object.