JavaScript Object seal() Method

TheObject.seal() method prevents new properties from being added to an object. However, it still lets you modify the existing properties of the object.

Let's see how:

What Does Object.seal() Do?

Here's what happens when you use Object.seal():

  • Prevents Adding New Properties: You cannot add new properties to the object.
  • Prevents Deleting Properties: You cannot remove existing properties from the object.
  • Allows Modifying Existing Properties: You can still change the values of the existing properties.

How to

We can "seal" an object by using Object.seal(yourObject).

Let's look at a simple example to understand how Object.seal() works:

// Creating an object
let car = {
  brand: "Toyota",
  model: "Corolla"
};

// Sealing the object
Object.seal(car);

// Trying to add a new property
car.year = 2024;
console.log(car.year); // Output: undefined (Cannot add new property)

// Trying to delete an existing property
delete car.model;
console.log(car.model); // Output: "Corolla" (Cannot delete existing property)

// Modifying an existing property
car.brand = "Honda";
console.log(car.brand); // Output: "Honda" (Can modify existing property)

Checking if an Object is Sealed

You can check if an object is sealed using Object.isSealed() method. This method returns true if the object is sealed and false otherwise.

// Example checking if Object is sealed
let car = {
  brand: "Toyota",
  model: "Corolla"
};

Object.seal(car);
console.log(Object.isSealed(car)); // Output: true
JavaScript
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.