The Object isExtensible() method

By

Learn how the JavaScript Object.isExtensible() method checks if you can add properties to an object, returning false after freeze, seal, or preventExtensions.

~~~

Object.isExtensible() checks if we can add new properties to an object. It returns true when we can, false when we can’t.

Any object is extensible, unless it’s been used as an argument to

Usage:

const dog = {}
Object.isExtensible(dog) //true
const cat = {}
Object.freeze(cat)
Object.isExtensible(cat) //false

Why does this method exist?

JavaScript objects are open by default. Any code that holds a reference to an object can attach new properties to it, at any time.

Sometimes you want to lock that down. Maybe you’re building a configuration object that should stay exactly as you defined it, and you call Object.preventExtensions() on it.

Object.isExtensible() is how you check that state later. Before adding a property to an object you didn’t create, you can test whether the operation will actually work:

const config = { port: 3000 }
Object.preventExtensions(config)

Object.isExtensible(config) //false

The three locking methods

The three methods that make an object non-extensible do different amounts of locking.

Object.preventExtensions() is the lightest. You can’t add new properties, but you can still change existing values and delete properties.

Object.seal() also stops you from deleting properties.

Object.freeze() locks everything: no adding, no deleting, no changing values.

All three make Object.isExtensible() return false, because all three include the “no new properties” restriction. So a false result tells you adding will fail, but not which level of locking was applied. Pair it with Object.isSealed() and Object.isFrozen() if you need the full picture.

What happens when you add a property anyway?

Here’s the pitfall. In non-strict mode, adding a property to a non-extensible object fails silently:

const config = { port: 3000 }
Object.preventExtensions(config)

config.host = 'localhost'
config.host //undefined

No error, no warning. The assignment just doesn’t happen, and you find out later when config.host is undefined.

In strict mode, the same assignment throws a TypeError, which is much easier to debug. One more reason to keep 'use strict' on, or use ES modules where strict mode is the default.

One last detail: if you pass a primitive like a number or a string, Object.isExtensible() returns false. Primitives are not objects, so there’s nothing to extend.

~~~

Related posts about js: