DEV Community

Joe Steinbring
Joe Steinbring

Posted on • Originally published at blog.jws.app on

1 1

Object.seal() vs Object.freeze()

So, you want to protect an object that you created in JavaScript? With Object.seal() and Object.freeze(), you have two solid options that do slightly different things. While Object.seal() prevents new properties from being added to the object and marks all existing properties as non-configurable, it still lets you change the values of properties. Object.freeze() on the other hand prevents new properties from being added to the object, prevents existing properties from being removed, and prevents the values of existing properties from being changed.

Let’s take a look at two examples.

In the above example, we seal the object on line 14 and then test changing a property, adding a property, and deleting a property.

In the next example, we freeze the object on line 14 and then do the same thing to its properties.

You will notice that Object.isSealed() and Object.isFrozen() are also available for testing the objects.

Have a question, comment, concern, etc? Feel free to drop a comment, below.

The post Object.seal() vs Object.freeze() first appeared on Blog.jws.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more