@a11d/is-writable
v1.0.2
Published
A function on the Object constructor that determines if a property is writable.
Maintainers
Readme
@a11d/is-writable
Check if an object property is writable, accounting for property descriptors, getters/setters, and the prototype chain.
import '@a11d/is-writable'
const obj = { name: 'John' }
Object.defineProperty(obj, 'id', { value: 123, writable: false })
Object.isWritable(obj, 'name') // true
Object.isWritable(obj, 'id') // falseInstallation
npm install @a11d/is-writableAPI
Returns true if the property is writable, false otherwise.
const obj = {}
Object.defineProperty(obj, 'readonly', { value: 42, writable: false })
Object.isWritable(obj, 'readonly') // false
Object.isWritable(obj, 'newProp') // true (non-existent properties are writable)Checks the entire prototype chain:
class Base {
get value() { return 1 }
}
class Child extends Base {}
Object.isWritable(new Child(), 'value') // false (getter-only in prototype)Behavior
Returns false for all properties on frozen objects:
const obj = { name: 'John' }
Object.freeze(obj)
Object.isWritable(obj, 'name') // false
Object.isWritable(obj, 'newProp') // falseGetter-only properties are not writable:
const obj = {
get value() { return 42 }
}
Object.isWritable(obj, 'value') // falseProperties with both getter and setter are writable:
const obj = {
get value() { return this._value },
set value(v) { this._value = v }
}
Object.isWritable(obj, 'value') // trueSetter-only properties are writable:
const obj = {
set value(v) { console.log(v) }
}
Object.isWritable(obj, 'value') // trueProperties that don't exist are considered writable (unless the object is frozen):
const obj = {}
Object.isWritable(obj, 'newProp') // trueChecks all descriptors in the prototype chain:
class Base {
get value() { return 1 }
}
class Child extends Base {
get value() { return 2 }
set value(v) { /* add setter alongside getter */ }
}
Object.isWritable(new Base(), 'value') // false (getter-only)
Object.isWritable(new Child(), 'value') // true (has both getter and setter)