Setting a Property’s Flags

Your proof card now has its own title and price, plus a category it finds on its defaults object. The next thing it needs is an ID, "P-17", that the proof desk can read but nobody can overwrite by accident. A customer approves a run by its ID, so a typo that rebinds it would print the wrong job.

In the Python class, that’s a read-only @property. In this lesson, you’ll find out what JavaScript keeps alongside a property’s value and how to choose those settings on purpose.

Read the Flags on a Property

The Python version stores the ID in an instance attribute and exposes it through a property with no setter:

Language: Python
class Card:
    category = "print"

    def __init__(self, title, price):
        self.title = title
        self.price = price
        self._id = "P-17"

    @property
    def id(self):
        return self._id

Ask the instance what it stores, then try to rebind the ID. The traceback is trimmed to its last line:

Language: Python
>>> card = Card("Harbour", 12)
>>> vars(card)
{'title': 'Harbour', 'price': 12, '_id': 'P-17'}
>>> card.id = "P-18"
Traceback (most recent call last):
  ...
AttributeError: property 'id' of 'Card' object has no setter

The instance’s __dict__ is a plain dictionary with no per-key rules. The protection lives on the class, in the property object. JavaScript works the other way around. Every property on an object carries its own small record of settings, called a property descriptor, and you can read it with Object.getOwnPropertyDescriptor(). As its name says, it only reads own properties, so for the card’s inherited category it returns undefined.

Python calls property a descriptor too, but there it’s an object on the class whose methods run on every access. A JavaScript descriptor is a plain object that describes one property’s settings.

The JavaScript examples run as ECMAScript (ES) modules. To run one yourself, save it as card.js next to a package.json file that holds { "type": "module" }, then run node card.js. Without that setting, Node runs these snippets as older CommonJS scripts, and some errors below would pass silently.

The JavaScript card comes from Object.create(defaults), as before. { category: "print" } is an object literal, JavaScript’s dict-like braces. const declares a name you can’t reassign, and console.log() prints a value:

Language: JavaScript
const defaults = { category: "print" };
const card = Object.create(defaults);
card.title = "Harbour";
card.price = 12;
console.log(Object.getOwnPropertyDescriptor(card, "title"));

The descriptor holds the value and three yes-or-no flags:

Language: Program Output
{
  value: 'Harbour',
  writable: true,
  enumerable: true,
  configurable: true
}

A property that stores a value like this one is a data property, and the record printed above is its data descriptor. writable decides whether assignment can change the value. enumerable decides whether the property shows up in listings such as Object.keys(), for...in, spread, and JSON.stringify().

configurable decides whether you can delete the property or redefine its flags. A non-configurable property can still be locked further, but never unlocked. When assignment adds a new property, it sets all three flags to true.

Fall Into the All-False Default

To set flags yourself, you call Object.defineProperty() with the object, the key, and a descriptor. The port of Python’s read-only property names the value and the one flag the ID needs:

Language: JavaScript
const defaults = { category: "print" };
const card = Object.create(defaults);
card.title = "Harbour";
card.price = 12;
Object.defineProperty(card, "id", { value: "P-17", writable: false });
console.log(card.id);
console.log(Object.keys(card));

Before you run it, predict both lines. Will the proof desk’s listing include id? Here’s what JavaScript prints:

Language: Program Output
P-17
[ 'title', 'price' ]

The ID reads fine, but it’s missing from the listing. To find out why, print the title’s descriptor and the ID’s side by side. From here on, the snippets start from a plain object literal, because the prototype plays no part in an own property’s flags:

Language: JavaScript
const card = { title: "Harbour", price: 12 };
Object.defineProperty(card, "id", { value: "P-17", writable: false });
console.log(Object.getOwnPropertyDescriptor(card, "title"));
console.log(Object.getOwnPropertyDescriptor(card, "id"));

The title created by the object literal has every flag set to true. The defined ID has every flag set to false, including the two you never mentioned:

Language: Program Output
{
  value: 'Harbour',
  writable: true,
  enumerable: true,
  configurable: true
}
{
  value: 'P-17',
  writable: false,
  enumerable: false,
  configurable: false
}

So when you create a new property, assignment sets every flag to true, and Object.defineProperty() sets every flag you don’t list to false. You use Object.defineProperty() when a property should be special, so it starts locked down and you opt in to each permission.

writable: false is the part the proof desk asked for. The other two came along unasked. enumerable: false dropped the ID from the listing, and configurable: false means nobody can delete or redefine it. In the snippet below, try runs a block, catch receives the error if the block throws, and err.name holds the error’s type. delete removes a property, as del does in Python:

Language: JavaScript
const card = { title: "Harbour", price: 12 };
Object.defineProperty(card, "id", { value: "P-17", writable: false });
try {
  card.id = "P-18";
} catch (err) {
  console.log(err.name);
}
try {
  delete card.id;
} catch (err) {
  console.log(err.name);
}

Both operations fail:

Language: Program Output
TypeError
TypeError

A TypeError is JavaScript’s error for an operation the value doesn’t allow, much like the AttributeError Python raised. The first one is the protection you wanted, and the second is configurable: false at work. Both operations throw because ES modules always run in strict mode, where a refused write or delete throws instead of being silently ignored.

enumerable: false only keeps the ID out of listings. Anyone who knows the name can still read card.id, and Object.getOwnPropertyNames() lists every own string key, enumerable or not:

Language: JavaScript
const card = { title: "Harbour", price: 12 };
Object.defineProperty(card, "id", { value: "P-17", writable: false });
console.log(Object.getOwnPropertyNames(card));

The ID is right there:

Language: Program Output
[ 'title', 'price', 'id' ]

Like Python’s _id, which vars(card) showed in plain view, a non-enumerable property is out of the way without being hidden, except that JavaScript, not convention, keeps it out of listings. It suits bookkeeping you want out of loops and copies. For real privacy, you’ll use private class fields or a closure, which come later.

Say Every Flag You Mean

Write every flag the property needs so that you make an explicit decision instead of relying on defaults. For the proof ID, that means listed, read-only, and permanent. Once a customer has approved a run by its ID, nobody should change or remove that ID, even on purpose. A title is different, because the proof desk sometimes needs to correct it, as you’ll see in a moment.

You can’t repair the card with the non-enumerable ID in place. Its ID is already non-configurable, so redefining it with enumerable: true throws a TypeError. A non-configurable property’s enumerable flag has to be right when you first define it, so this snippet starts from a fresh card:

Language: JavaScript
const card = { title: "Harbour", price: 12 };
Object.defineProperty(card, "id", {
  value: "P-17",
  enumerable: true,
  writable: false,
  configurable: false,
});
console.log(Object.keys(card));
console.log(JSON.stringify(card));

Now the ID appears wherever the card is listed or serialized:

Language: Program Output
[ 'title', 'price', 'id' ]
{"title":"Harbour","price":12,"id":"P-17"}

The defaults apply only when the property is new. Call Object.defineProperty() on a property that already exists, and every flag you omit keeps its current value. Here, the proof desk locks the title against assignment, then corrects it on purpose:

Language: JavaScript
const card = { title: "Harbour", price: 12 };
Object.defineProperty(card, "title", { writable: false });
console.log(Object.getOwnPropertyDescriptor(card, "title"));
Object.defineProperty(card, "title", { value: "Harbour at Dusk" });
console.log(card.title);

The title keeps enumerable and configurable from the object literal, and the redefinition goes through:

Language: Program Output
{
  value: 'Harbour',
  writable: false,
  enumerable: true,
  configurable: true
}
Harbour at Dusk

writable and configurable guard different operations. writable: false blocks card.title = ..., while configurable: true still allows deleting the property or redefining it with Object.defineProperty().

Python’s id property has no setter and no deleter, so it blocks both card.id = ... and del card.id under one rule that the class sets for every instance. It only guards the name, though. The value sits in _id, where card._id = "P-18" changes card.id without an error. In JavaScript, the flags sit on the property itself, so writable and configurable control these operations separately for this one property on this one object.

So when you create a property with Object.defineProperty(), spell out writable, enumerable, and configurable. When an assignment throws, a key goes missing from a listing, or a delete fails, read the descriptor first. If the property is the card’s own, its descriptor tells you which flag is responsible.

In the next exercise, Lock the Proof Identifier, you’ll set up the ID for a new, unapproved proof, P-24, so the public listing shows it, an accidental rebinding fails, and the proof desk can still redefine it deliberately.

Become a Member to join the conversation.