JavaScript Object Property Flags and Descriptors

— Modifying objects with descriptors and writable, enumerable and configurable flags.

Photo by Philippine FITAMANT on Unsplash
class Person {
constructor(name) {
this.name = name;
}
this.age = age
}
Person.prototype.greeting = `Hi! I'm ${this.name}`

Enumerable

var o = {};Object.defineProperty(o, 'a', {
value: 1,
enumerable: true
});
Object.defineProperty(o, 'b', {
value: 2,
enumerable: false
});
for (var i in o) {
console.log(i);
} //'a'
Object.keys(o); // ['a']

Writable

'use strict'
var o = {};
Object.defineProperty(o, 'a', {
value: 37,
writable: false
});
console.log(o.a); // 37
o.a = 25; // throws a TypeError

Configurable

var o = {};Object.defineProperty(o, 'a', {
get() { return 1; },
configurable: false
});

Object.defineProperty(o, 'a', {
set() {}
}); // throws a TypeError (set was undefined previously)
Object.defineProperty(o, 'a', {
get() { return 1; }
}); // throws a TypeError
// (even though the new get does exactly the same thing)
Object.defineProperty(o, 'a', {
value: 12
}); // throws a TypeError // ('value' can be changed when 'configurable' is false but not in this case due to 'get' accessor)

Object.defineProperty(obj, prop, descriptor)

const object1 = {};Object.defineProperty(object1, ‘property1’, {
value: 42,
writable: false
});
var o = {};o.a = 1;
// is equivalent to:
Object.defineProperty(o, 'a', {
value: 1,
writable: true,
configurable: true,
enumerable: true

});
Object.defineProperty(o, 'a', { value: 1 });
// is equivalent to:
Object.defineProperty(o, 'a', {
value: 1,
writable: false,
configurable: false,
enumerable: false

});

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store