completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

Declaring attributes

Declare web component attributes once, then generate getters, setters, and attribute converters, reflect them without loops, and write it all as decorators.

By the end, you can
  • 01
    Declare attributes onceDescribe each attribute in one static attributes map, and let the base class turn it into observed attributes and properties.
  • 02
    Convert and reflect safelyRead attribute text with HTML's rules and a fallback, write your own converter, and reflect without an endless loop.
  • 03
    Use decorators for attributesWrite the same declarations as standard or legacy TypeScript decorators, and know why both need a build step.

How do you declare attributes in a web component?

Ravi is adding a cup to the Leaf and Kettle order screen. It needs a size, a roast, and an iced switch. He starts a getter, a setter, and a callback for the size. Then he stops.

Two more attributes means two more of each. Every one turns text into a number, a word, or true and false. Can he describe each attribute once, and get the rest?

Yes. Declare each attribute once, in a list on the class: its type, its default, and whether it reflects. A base class reads the list and makes the rest: the watched attribute, a property, the conversion from text, and the write back.

Here is a cup built that way. Press the button:

A cup whose attributes are declaredPop out in the code editor (opens in a new tab)HTML
<tea-cup size="4" roast="dark">Hojicha</tea-cup><button id="bigger">Bigger and iced</button><script type="module">  import "./tea-cup.js";  const cup = document.querySelector("tea-cup");  console.log(`size: ${cup.size} (${typeof cup.size}), roast: ${cup.roast}`);  document.querySelector("#bigger").addEventListener("click", () => {    cup.size += 1;    cup.iced = true;    console.log(cup.outerHTML);  });</script>
ResultLoading…
  • Line 1 is a cup with a size of 4 and a dark roast.
  • Line 6 prints the size, its type, and the roast.
  • Lines 8 and 9 make the cup one size bigger, and iced. Line 10 prints the cup's HTML.

It prints size: 4 (number), roast: dark. The attribute holds the text 4, but the property is the number 4. So cup.size += 1 gives 5, where text would give 41. After the press, it prints <tea-cup size="5" roast="dark" iced="">Hojicha</tea-cup>. The cup says size 5, dark roast, iced, with a dashed border.

Now the whole cup:

tea-cup.js: three attributes, declaredJavaScript
import { TeaElement } from "./element.js";

export class TeaCup extends TeaElement {
  static attributes = {
    size: { type: Number, reflect: true, fallback: 3 },
    roast: { values: ["light", "dark"], fallback: "light" },
    iced: { type: Boolean, reflect: true },
  };
  static styles = [`
    :host { display: inline-block; padding: 0 8px; border: 2px solid seagreen; border-radius: 8px; }
    :host([iced]) { border-style: dashed; }
  `];
  static template = `<slot></slot>: <span id="order"></span>`;

  render() {
    const iced = this.iced ? ", iced" : "";
    this.renderRoot.getElementById("order").textContent = `size ${this.size}, ${this.roast} roast${iced}`;
  }
}

customElements.define("tea-cup", TeaCup);
  • Lines 4 to 8 are the declarations. Line 5: size is a number, it reflects, and it's 3 when missing.
  • Line 6: roast is light or dark, light by default. Line 7: iced is on or off, and reflects.
  • Lines 15 to 18 draw the cup from this.size, this.roast, and this.iced.

There's no getter, no setter, and no attributeChangedCallback(). Three lines describe three attributes.

On the left, a card for static attributes, with size: Number, reflects under it. Four arrows lead from it to four cards on the right. The first says watches size, with observedAttributes under it. The second says cup.size property, with on the prototype under it. The third says text 4 becomes the number 4, with fromAttribute() under it. The fourth says the number 5 becomes text 5, with toAttribute() under it.static attributessize: Number, reflectswatches sizeobservedAttributescup.size propertyon the prototype"4" becomes 4fromAttribute()5 becomes "5"toAttribute()
One line of the map, size: { type: Number, reflect: true, fallback: 3 }, gives the cup four things: a watched attribute, a property, a way to read its text, and a way to write it back.
Real-life analogyAn order form with fixed boxes

The tea room's order form has a box for each choice. The size box takes a number. The roast has two circles, light and dark. Iced is a tick box. Every waiter fills in the same form. When a box is empty or messy, the kitchen makes the house choice.

In real life: The printed order form
In JavaScript: static attributes on the class
In real life: A box that takes a number
In JavaScript: type: Number
In real life: Two circles, light and dark
In JavaScript: values: ["light", "dark"]
In real life: A tick box
In JavaScript: type: Boolean
In real life: The house choice for an empty or messy box
In JavaScript: fallback
The main idea

Declare each attribute once. Give it a type, a default, and say whether it reflects. The base class reads the declarations once, and makes the watched attribute, the property, the conversion, and the reflection.

Lesson 5.1 wrote these parts by hand. Lesson 5.2 gave the rules for reading text. This lesson writes them once, in TeaElement, the base class from lesson 19.1.

What goes in an attribute declaration?

A declaration is an object of options. Each option answers one question about the attribute. Read each row across:

The options a declaration can have
OptionWhat it doesIn the cup
typeHow the text is read: String (the default), Number, or Boolean.size is a Number, and iced is a Boolean.
valuesThe only words allowed, in any case. Anything else gives the fallback.roast takes light or dark.
fallbackThe value when the attribute is missing, or its text makes no sense.size falls back to 3, and roast to light.
reflectWrite the property back to the attribute when code sets it.size and iced reflect. roast doesn't.
attributeA different attribute name. Without it, giftWrapped watches gift-wrapped.The cup's names need no change.
converterYour own fromAttribute() and toAttribute(), in place of the rules above.The cup doesn't need one. A steeping time does.

Lit's static properties uses type, reflect, attribute, and converter the same way (Lit). values and fallback are the kit's own. They copy what built-in elements do with bad text.

TeaElement reads the map in finalize(), which runs once per class. Here it is, with its new lines:

element.js: finalize() reads the declarationsJavaScript
  static get observedAttributes() {
    return this.finalize().observed;
  }

  static finalize() {
    if (Object.hasOwn(this, "finalized")) return this.finalized;
    const parent = Object.getPrototypeOf(this).finalize?.() ?? start;
    const own = (name, none) => (Object.hasOwn(this, name) ? this[name] : none);
    const markup = own("template", "");
    const attributes = new Map(parent.attributes);
    for (const [name, options] of Object.entries({ ...own("attributes", {}), ...decorated(this) })) {
      const declaration = { name, attribute: dashed(name), ...options, ...converterFor(options) };
      attributes.set(declaration.attribute, declaration);
      this.createProperty(declaration);
    }
    this.finalized = {
      observed: [...new Set([...parent.observed, ...own("observed", []), ...attributes.keys()])],
      attributes,
      sheets: [...parent.sheets, ...own("styles", []).map(toSheet)],
      template: markup ? toTemplate(markup) : parent.template,
    };
    return this.finalized;
  }
  • Lines 1 to 3: define() reads observedAttributes once, which finalizes the class.
  • Line 10 starts from the parent class's attributes, so a subclass adds to them.
  • Line 11 goes through the class's own static attributes, and any its decorators declared.
  • Line 12 makes a full declaration: the property's name, the attribute's name, the options, and two converter functions.
  • Line 13 files it under the attribute's name, for the callback. Line 14 makes the property.
  • Line 17 adds every declared attribute to the observed list, once each.

Why build the list here? The browser reads observedAttributes once, in define() (lesson 3.4). And attributeChangedCallback() runs only for names in that list (MDN). So the declarations must be ready by then. Static fields are.

Line 12 also calls dashed(), near the end of element.js. It turns a camelCase name into a dashed one, as the platform does: ariaChecked reflects aria-checked (MDN). Try a subclass:

A gift cup adds one attribute to the cup's threePop out in the code editor (opens in a new tab)HTML
<tea-cup size="4">Hojicha</tea-cup><gift-cup gift-wrapped>Sencha</gift-cup><script type="module">  import { TeaCup } from "./tea-cup.js";  class GiftCup extends TeaCup {    static attributes = { giftWrapped: { type: Boolean, reflect: true } };  }  customElements.define("gift-cup", GiftCup);  console.log(`TeaCup watches: ${TeaCup.observedAttributes.join(", ")}`);  console.log(`GiftCup watches: ${GiftCup.observedAttributes.join(", ")}`);  console.log(`giftWrapped: ${document.querySelector("gift-cup").giftWrapped}`);</script>
ResultLoading…
  • Line 2 is a gift cup with gift-wrapped.
  • Lines 5 to 7: GiftCup extends TeaCup and declares one more attribute.
  • Lines 9 to 11 print what each class watches, and the gift cup's new property.

It prints TeaCup watches: size, roast, iced, then GiftCup watches: size, roast, iced, gift-wrapped, then giftWrapped: true. The subclass kept its parent's three and added one. Why it matters: a component can grow a parent's attributes without copying them.

How does a base class generate getters and setters?

It writes them once, on the class's prototype: the object every element of the class shares. When code reads cup.size, JavaScript looks on the cup first, then on its prototype (the prototype chain). Line 14 of finalize() calls this:

element.js: createProperty() makes one getter and one setterJavaScript
  static createProperty({ name, attribute, reflect, fromAttribute, toAttribute }) {
    Object.defineProperty(this.prototype, name, {
      get() {
        return this.#values.has(name) ? this.#values.get(name) : fromAttribute(null);
      },
      set(value) {
        const oldValue = this[name];
        const text = toAttribute(value);
        this.#values.set(name, fromAttribute(text));
        if (reflect && this.#reflecting !== name) {
          this.#reflecting = name;
          if (text === null) this.removeAttribute(attribute);
          else this.setAttribute(attribute, text);
          this.#reflecting = null;
        }
        if (this.isConnected) this.requestUpdate(name, oldValue);
      },
      configurable: true,
      enumerable: true,
    });
  }
  • Line 2 calls Object.defineProperty(). It adds a property with a getter and a setter to an object, here the prototype (MDN, and property descriptors).
  • Line 4 is the getter. It gives the stored value. With none stored, it asks the converter about a missing attribute, which gives the fallback.
  • Lines 7 to 9 start the setter. Line 8 turns the new value into attribute text. Line 9 reads that text back, and stores the result. The converters section shows why.
  • Lines 10 to 15 write the attribute, for a declaration that reflects. The reflection section explains line 10.
  • Line 16 asks for an update, as lesson 18.1's setters did.

Where do the values live? In #values, a private Map on each element, on line 11 of element.js. A private field starts with #, and only code inside the class can use it. So all cups share one getter and setter, and each keeps its own size. Check it:

The generated property lives on the prototypePop out in the code editor (opens in a new tab)HTML
<tea-cup size="4">Hojicha</tea-cup><tea-cup>Sencha</tea-cup><script type="module">  import { TeaCup } from "./tea-cup.js";  const [first, second] = document.querySelectorAll("tea-cup");  const size = Object.getOwnPropertyDescriptor(TeaCup.prototype, "size");  console.log(`On the prototype: get is a ${typeof size.get}, set is a ${typeof size.set}`);  console.log(`On the first cup itself: ${Object.hasOwn(first, "size")}`);  console.log(`Sizes: ${first.size} and ${second.size}`);</script>
ResultLoading…
  • Line 6 asks the prototype for its size property. Line 7 prints what kind its getter and setter are.
  • Line 8 asks whether the first cup has a size of its own. Line 9 prints both sizes.

It prints On the prototype: get is a function, set is a function, then On the first cup itself: false, then Sizes: 4 and 3. The second cup has no attribute, so its getter gave the fallback.

At the top, TeaCup.prototype holds one card: get size, set size. Below are three cups. Cup 1 holds 4, and an arrow goes up from it to the prototype. Cup 2 holds nothing, and an arrow goes up from it too: the getter gives 3. Cup 3 holds its own size = 2, a class field, and has no arrow: the setter never runs.TeaCup.prototypeget size, set sizecup 1: 4cup 2: nothingcup 3: size = 2a value in #valuesthe getter gives 3a field hides them
Every cup shares the one getter and setter on TeaCup.prototype. Each keeps only its value. A class field gives cup 3 its own size, so JavaScript never reaches the prototype's.
Real-life analogyOne price board, and a note on one table

Leaf and Kettle has one price board on the wall. Every table reads it, so Ravi changes a price in one place. One day a waiter sticks a note on table 4: "Tea: 2". The guests there read the note and never look up. When Ravi changes the board, table 4 doesn't notice.

In real life: The price board on the wall
In JavaScript: The getter and setter on TeaCup.prototype
In real life: Each table's own order
In JavaScript: Each cup's value in #values
In real life: A note stuck on table 4
In JavaScript: A class field: the cup's own property
In real life: Guests reading the note, not the board
In JavaScript: JavaScript finding the own property first

Why does a class field break a generated property?

Ravi wants a size of 2 by default. He writes size = 2; in the class. That's a class field: a property each new element gets. Lesson 4.2 showed a field hiding a hand-written setter. Try it against a generated one:

Playground: the default as a class field, or as fallback
Two cups, one with a size and one withoutPop out in the code editor (opens in a new tab)HTML
<tea-cup size="4">Hojicha</tea-cup><tea-cup>Sencha</tea-cup><script type="module">  import "./tea-cup.js";  const cup = document.querySelector("tea-cup");  console.log(`size is the cup's own property: ${Object.hasOwn(cup, "size")}`);</script>
ResultLoading…
Try it yourself
The field covers the generated property

Each cup gets its own size property after super() returns. It sits in front of the prototype's getter and setter, so TeaElement stops with an error.

Only lines 5 and 14 of the tea-cup.js tab change.
  • Lines 1 and 2 are two cups, one with a size and one without.
  • Line 6 prints whether the first cup has a size of its own.

With the class field, it prints size is the cup's own property: true, and the same error twice: Error: tea-cup: the class field size hides its generated property. Both cups are blank. With fallback: 2, it prints false. The cups say size 4, light roast and size 2, light roast.

JavaScript adds a class field to each new element right after super() returns. It's the cup's own property, so JavaScript finds it before the prototype's getter and setter. Lit's docs describe the same trap (Lit). How does TeaElement catch it? In connectedCallback():

element.js: connectedCallback() looks for class fieldsJavaScript
  connectedCallback() {
    for (const { name } of this.constructor.finalize().attributes.values()) {
      if (Object.hasOwn(this, name)) {
        throw new Error(`${this.localName}: the class field ${name} hides its generated property`);
      }
    }
    for (const [name, value] of this.#early) this[name] = value;
    this.#early.clear();
    this.requestUpdate();
  }
  • Lines 2 to 6 throw when a declared name is the element's own property.
  • Line 7 hands values a page set before the class loaded to their setters, as lesson 4.2's pattern did. Line 8 forgets them.

Those early values were taken first, by the constructor, on lines 63 to 67 of element.js. It deletes them in TeaElement, before any subclass field exists (Nolan Lawson explains early values). So when a cup connects, an own property can only be a class field. Lit's development build throws the same kind of error, at its first update (lines 1452 to 1471).

TypeScript adds a twist. A field and an assignment look alike, but they do different things:

A class field doesn't call a setter, and an assignment doesPop out in the code editor (opens in a new tab)JavaScript
class Cup {
  set size(value) {
    console.log(`The setter got ${value}`);
  }
}
class FieldCup extends Cup {
  size = 2;
}
class AssignedCup extends Cup {
  constructor() {
    super();
    this.size = 2;
  }
}
new FieldCup();
new AssignedCup();

It prints The setter got 2 once, for AssignedCup. Line 7's field makes a new property. Line 12's assignment calls the setter (assignment and definition). TypeScript writes your field either way, by its useDefineForClassFields setting (TypeScript). Read each row across:

What TypeScript writes for size = 2;
useDefineForClassFieldsWhat TypeScript writes
true, the default for an ES2022 targetsize = 2;, a class field. It hides the setter.
falsethis.size = 2; in the constructor. It calls the setter.

Lit asks TypeScript users of its legacy decorators for false (Lit). In TeaElement, the setter would then run in the constructor, and a reflecting setter would add an attribute. Lesson 3.2 showed what document.createElement() does then: it reports a NotSupportedError. So the kit takes every default from fallback.

How do attribute converters work?

An attribute is always text. A converter is a pair of functions that turn it into a value, and back. fromAttribute() reads text, and toAttribute() writes it. TeaElement builds the pair for each declaration in converters.js:

converters.js: a converter for each kind of attributeJavaScript
import { toFloat, toKeyword } from "./attribute-types.js";

const toText = (value) => (value === null || value === undefined ? null : String(value));

export function converterFor({ type = String, values, fallback = null, converter }) {
  if (converter) return converter;
  if (type === Boolean) return { fromAttribute: (text) => text !== null, toAttribute: (value) => (value ? "" : null) };
  if (values) return { fromAttribute: (text) => toKeyword(text, values, fallback), toAttribute: toText };
  if (type === Number) return { fromAttribute: (text) => toFloat(text, fallback), toAttribute: toText };
  return { fromAttribute: (text) => text ?? fallback, toAttribute: toText };
}
  • Line 3 turns any value into text. null and undefined give null, which means no attribute.
  • Line 6: a declaration with its own converter keeps it.
  • Line 7: a Boolean is true whenever the attribute is there. Writing true gives empty text, and false removes it.
  • Line 8: a keyword uses toKeyword(). It matches in any case, and gives the fallback for other words.
  • Line 9: a number uses toFloat(), HTML's rules for decimals, with the fallback.
  • Line 10: text stays text, or gives the fallback when it's missing.

Lines 8 and 9 reuse the kit's attribute-types.js, from lesson 5.2. It follows the HTML Standard, like built-in elements do.

Two columns: the attribute on the left, the property on the right. Row 1: the text 4 cups goes right through fromAttribute() and becomes the number 4. Row 2: the number 5 goes left through toAttribute() and becomes the text 5. Row 3: the text big goes right through fromAttribute() and becomes 3, the fallback.the attributethe property"4 cups"fromAttribute()4"5"toAttribute()5"big"fromAttribute()3the fallback
fromAttribute() reads text with HTML's rules, and gives the fallback when it can't. toAttribute() writes a value back as text.
Real-life analogyA translator at the counter

A visitor orders in French. Asha puts it into English for the kitchen, and puts the kitchen's answer back into French. When she can't make out a word, she orders the house tea, as the menu says to.

In real life: Asha, the translator
In JavaScript: A converter
In real life: French into English, for the kitchen
In JavaScript: fromAttribute(): text into a value
In real life: English back into French
In JavaScript: toAttribute(): a value back into text
In real life: A word she can't make out
In JavaScript: Bad text, which gives the fallback

Type any text. The page writes it into all three attributes, and shows what each property makes of it:

One text, read as a number, a keyword, and a booleanPop out in the code editor (opens in a new tab)HTML
<label>Text for all three attributes <input id="text" value="4 cups"></label><button id="remove">Remove them</button><p><tea-cup>Sencha</tea-cup></p><output></output><script type="module">  import "./tea-cup.js";  const cup = document.querySelector("tea-cup");  const text = document.querySelector("#text");  const names = ["size", "roast", "iced"];  const show = () => {    document.querySelector("output").textContent = `size ${cup.size}, roast ${cup.roast}, iced ${cup.iced}`;  };  text.addEventListener("input", () => {    for (const name of names) cup.setAttribute(name, text.value);    show();  });  document.querySelector("#remove").addEventListener("click", () => {    for (const name of names) cup.removeAttribute(name);    show();  });  for (const name of names) cup.setAttribute(name, text.value);  show();</script>
ResultLoading…
  • Line 9 names the three attributes. Lines 13 to 16 write the box's text into each one, as you type.
  • Lines 17 to 20: Remove them takes all three away.

It starts with 4 cups and shows size 4, roast light, iced true. The number rules read the 4 and stop at the space. Type DARK: size 3, roast dark, iced true. Type false: size 3, roast light, iced true. An iced attribute that's there is on, even with the text false. Press Remove them: size 3, roast light, iced false.

Why does the setter send a value through text, on lines 8 and 9 of createProperty()? So a property follows the attribute's rules. cup.roast = "burnt" stores light, like roast="burnt" does. Built-in elements behave the same: input.type = "burnt" gives back text (Jake Archibald). Lit doesn't. Its docs say a property keeps whatever value you assign (Lit).

A converter of your own

Some values need their own rules. A steeping time reads best as minutes and seconds, like 2:30. Press the button:

A brew with a converter for minutes and secondsPop out in the code editor (opens in a new tab)HTML
<tea-brew steep="2:30">Sencha</tea-brew><button id="longer">30 seconds longer</button><script type="module">  import "./tea-brew.js";  const brew = document.querySelector("tea-brew");  console.log(`steep: ${brew.steep} seconds`);  document.querySelector("#longer").addEventListener("click", () => {    brew.steep += 30;    console.log(`steep="${brew.getAttribute("steep")}"`);  });</script>
ResultLoading…

It prints steep: 150 seconds. Press 30 seconds longer, and it prints steep="3:00". The brew says Sencha: steep for 180 seconds. Here is the converter, in the tea-brew.js tab:

tea-brew.js: fromAttribute() and toAttribute() for a steeping timeJavaScript
import { TeaElement } from "./element.js";

const minutesAndSeconds = {
  fromAttribute(text) {
    const match = /^(\d+):([0-5]\d)$/.exec(text ?? "");
    return match ? Number(match[1]) * 60 + Number(match[2]) : 180;
  },
  toAttribute(seconds) {
    const whole = Math.round(seconds);
    return `${Math.floor(whole / 60)}:${String(whole % 60).padStart(2, "0")}`;
  },
};

export class TeaBrew extends TeaElement {
  static attributes = {
    steep: { converter: minutesAndSeconds, reflect: true },
  };
  static template = `<slot></slot>: steep for <span id="seconds"></span> seconds`;

  render() {
    this.renderRoot.getElementById("seconds").textContent = this.steep;
  }
}

customElements.define("tea-brew", TeaBrew);
  • Lines 3 to 12 are the converter: an object with the two functions.
  • Line 5 matches minutes, a colon, and two digits of seconds. Line 6 gives the total seconds, or 180 when the text doesn't match.
  • Lines 9 and 10 write seconds back as minutes and seconds, with a leading zero.
  • Line 16 declares steep with that converter. It reflects.

A date works the same way. Lit's tutorial on custom converters builds one for dates (Lit tutorial). Why it matters: any value that has a text form can be an attribute, with rules you choose.

How do you reflect a property without an endless loop?

Reflecting means writing a property back to its attribute (lesson 5.1). The setter does it on lines 10 to 15. But writing an attribute runs the callback, and the callback sets the property. Lesson 3.4 showed such a pair calling each other forever. First, when exactly does the callback run?

When attributeChangedCallback() runsPop out in the code editor (opens in a new tab)HTML
<tea-cup></tea-cup><script type="module">  class TeaCup extends HTMLElement {    static observedAttributes = ["size"];    attributeChangedCallback(name, oldValue, newValue) {      console.log(`2. attributeChangedCallback: ${name} is now ${newValue}`);    }  }  customElements.define("tea-cup", TeaCup);  const cup = document.querySelector("tea-cup");  new MutationObserver(() => console.log("4. MutationObserver")).observe(cup, { attributes: true });  console.log("1. setAttribute starts");  cup.setAttribute("size", "5");  console.log("3. setAttribute returned");</script>
ResultLoading…
  • Lines 3 to 8 are a plain cup class whose callback prints.
  • Line 11 starts a MutationObserver, which also hears about attribute changes.
  • Lines 12 to 14 print, set the attribute, and print again.

It prints 1. setAttribute starts, 2. attributeChangedCallback: size is now 5, 3. setAttribute returned, and 4. MutationObserver. The callback ran inside setAttribute(), before it returned. The observer heard later, in a microtask.

The HTML Standard says why. setAttribute() is marked [CEReactions]. The browser runs its steps, then the custom element callbacks they queued, and only then returns (HTML Standard).

Two lanes, the setter on the left and the callback on the right. The setter's first card sets #reflecting to size. An arrow goes down to its second card, setAttribute size 5. An arrow goes right to the callback's card: sees the mark, skips. An arrow comes back to the setter's third card, #reflecting = null, labelled back in the setter.the setterthe callback#reflecting = "size"setAttribute("size", "5")sees the mark, skipsback in the setter#reflecting = null
The callback runs inside setAttribute(), while the mark is still set. So it knows the change is the setter's own, and doesn't copy it back.

So the setter can leave a mark for its own callback. Back on lines 10 to 14 of createProperty(), line 11 sets #reflecting to the property's name. Line 13 writes the attribute. Line 14 clears the mark. The callback checks it:

element.js: attributeChangedCallback() skips its own writeJavaScript
  attributeChangedCallback(attribute, oldValue, newValue) {
    const declaration = this.constructor.finalize().attributes.get(attribute);
    if (!declaration) {
      if (oldValue !== newValue && this.isConnected) this.requestUpdate();
    } else if (this.#reflecting !== declaration.name) {
      this.#reflecting = declaration.name;
      this[declaration.name] = declaration.fromAttribute(newValue);
      this.#reflecting = null;
    }
  }
  • Line 2 finds the declaration for this attribute.
  • Line 4: an attribute that's only observed, like the badge's kind, asks for an update.
  • Line 5: a declared attribute, unless its own property is writing it right now.
  • Lines 6 to 8 set the property from the new text, with the mark on. So the setter's line 10 doesn't write the attribute back.
Real-life analogyHolding the marker

Ravi keeps today's teas on a whiteboard and in the till. When the board changes, he copies it into the till. When the till changes, he writes it on the board. There's one marker. A change he sees while holding it is his own, so he doesn't copy it back.

In real life: The whiteboard
In JavaScript: The attribute
In real life: The till
In JavaScript: The property
In real life: Holding the one marker
In JavaScript: #reflecting set to the property's name
In real life: Not copying his own change back
In JavaScript: The callback skipping its own write

Now take the mark away. Press Set size to 5 with each choice:

Playground: reflection with the guard, and without it
A cup and a button that sets its sizePop out in the code editor (opens in a new tab)HTML
<tea-cup>Hojicha</tea-cup><button id="five">Set size to 5</button><script type="module">  import "./tea-cup.js";  const cup = document.querySelector("tea-cup");  document.querySelector("#five").addEventListener("click", () => {    cup.size = 5;    console.log(`size ${cup.size}, attribute ${cup.getAttribute("size")}`);  });</script>
ResultLoading…
Try it yourself
The callback sees its own write, and stops

The setter marks size as reflecting, then writes the attribute. The callback runs inside setAttribute(), sees the mark, and skips the property.

Only lines 48 and 97 of the element.js tab change: the two checks of #reflecting.

With the guard, it prints size 5, attribute 5. Without it, the page reports RangeError: Maximum call stack size exceeded. The setter and the callback called each other until the call stack was full. Then the page carries on, and prints the same line. The browser reports an error thrown in a callback, instead of passing it to setAttribute()'s caller (HTML Standard). That's why this bug is easy to miss.

One mark covers both directions. Lit does the same with __reflectingProperty (lines 1183 to 1230 and 1233 to 1259). Its comment says the trick works because the callback is synchronous (lines 1213 to 1219).

What should a component do with a bad attribute value?

Use the default, and leave the attribute alone, as built-in elements do. Lesson 5.2 gave the rules. Here they are, next to the cup:

Bad text in two built-in elements and the cupPop out in the code editor (opens in a new tab)HTML
<input type="burnt"><button disabled="false">Order</button><tea-cup size="big" roast="burnt" iced="false">Sencha</tea-cup><script type="module">  import "./tea-cup.js";  const input = document.querySelector("input");  const button = document.querySelector("button");  const cup = document.querySelector("tea-cup");  console.log(`input.type: ${input.type}, button.disabled: ${button.disabled}`);  console.log(`size: ${cup.size}, roast: ${cup.roast}, iced: ${cup.iced}`);  const text = ["size", "roast", "iced"].map((name) => cup.getAttribute(name));  console.log(`The attributes still say: ${text.join(", ")}`);</script>
ResultLoading…
  • Line 1 is an input whose type is burnt. Line 2 is a button with disabled="false".
  • Line 3 is a cup with a bad size, a bad roast, and iced="false".
  • Lines 9 to 12 print the properties, then the attributes' text.

It prints input.type: text, button.disabled: true. Then size: 3, roast: light, iced: true: the cup falls back the same way. Then The attributes still say: big, burnt, false. Nothing rewrote the page's HTML.

Burton Smith asks for attributes that work "when set, unset, and poorly set" (his post). Here are the cup's three. Read each row across:

The cup's attributes, set well, not set, and set badly
AttributeSet wellNot setSet badly
sizesize="5" gives 5.No attribute gives 3.size="big" gives 3.
roastroast="DARK" gives dark.No attribute gives light.roast="burnt" gives light.
icediced="" gives true.No attribute gives false.iced="false" gives true.

One more rule: a default never becomes an attribute. On the converters page, Remove them left no attributes, and the size was still 3. Lit 3.3 added a useDefault option for this (changelog). It keeps a default from reflecting, and brings it back when the attribute goes (Lit).

Which attributes should reflect?

Every reflected change writes the HTML and runs the callback. Lesson 5.1 counted the cost. Cory LaViska's rules decide each reflect (his post):

  • Reflect settings the page writes and styles, like size, so tea-cup[size="5"] works.
  • Reflect states a person changes and others watch, like iced, open, or disabled.
  • Don't reflect objects, lists, or long text.
  • Internal state, like brewing, isn't an attribute at all. Show it with a custom state and :state(), as lesson 12.3 did. Don't declare it.

Lit's docs agree: attributes are input from the element's owner, so reflect sparingly (Lit). And when a rule is missing, the declarations grow without touching element.js: a subclass adds attributes, and a converter adds rules. Exercises 5 and 6 do both.

How do decorators declare attributes?

A decorator is a function you write after an @, in front of a class member. It runs once, when the class is made, and gets that member (decorators). Lit's @property() is one. TeaElement gets its own, attribute():

element.js: attribute(), a decorator for both kindsJavaScript
export function attribute(options = {}) {
  return (target, context) => {
    if (typeof context === "object") {
      if (!Object.hasOwn(context.metadata, "attributes")) context.metadata.attributes = {};
      context.metadata.attributes[context.name] = options;
    } else {
      const Class = target.constructor;
      if (!Object.hasOwn(Class, "attributes")) Class.attributes = {};
      Class.attributes[context] = options;
    }
  };
}

function decorated(Class) {
  const metadata = Object.hasOwn(Class, Symbol.metadata) ? Class[Symbol.metadata] : {};
  return Object.hasOwn(metadata, "attributes") ? metadata.attributes : {};
}
  • Line 1 takes the same options as static attributes. Line 2 returns the decorator.
  • Line 3 tells the two kinds apart. A standard decorator gets a context object, with the member's name and the class's metadata.
  • Lines 4 and 5 keep the options in the metadata. decorated(), lines 14 to 17, reads them back for finalize().
  • Lines 7 to 9: a legacy TypeScript decorator gets the prototype and the name (legacy decorators). It adds the options to the class's own static attributes.

Lit's property() tells them apart the same way (lines 205 to 233). Line 6 of element.js adds Symbol.metadata when it's missing, because TypeScript only keeps metadata when it exists. Lit does that too (lines 432 to 434). Here is the cup with standard decorators:

tea-cup.ts: the cup with standard decoratorsTypeScript
import { TeaElement, attribute } from "./element.js";

export class TeaCup extends TeaElement {
  @attribute({ type: Number, reflect: true, fallback: 3 })
  accessor size: number;

  @attribute({ values: ["light", "dark"], fallback: "light" })
  accessor roast: string;

  static template = `<slot></slot>: <span id="order"></span>`;

  render() {
    this.renderRoot.getElementById("order").textContent = `size ${this.size}, ${this.roast} roast`;
  }
}

customElements.define("tea-cup", TeaCup);
  • Lines 4 and 5 declare size: the decorator, then accessor size.
  • Lines 7 and 8 declare roast the same way.

accessor makes an auto-accessor: a getter and a setter on the prototype, with a private value behind them (auto-accessors). A standard decorator can't turn a field into a getter and setter, so it needs one already there (Lit 3 upgrade guide). finalize() then puts TeaElement's own in its place. The legacy version is the same, without the word accessor.

Real-life analogyA stamp on a parcel

At the post office, a clerk stamps FRAGILE on a parcel. The stamp doesn't change what's inside. It tells the sorting room, later, how to handle it.

In real life: The FRAGILE stamp
In JavaScript: @attribute({ type: Number })
In real life: The parcel it's on
In JavaScript: accessor size
In real life: The sorting room reading the stamps
In JavaScript: finalize() reading the metadata
In real life: Careful handling
In JavaScript: The generated property

Do decorators work in the browser without a build step?

No. Decorators are still a proposal: TC39, the group that designs JavaScript, lists them at stage 2.7 (TC39). No browser runs them yet. Can I use marks every version of Chrome, Edge, Firefox, and Safari as not supported (Can I use). Chrome refuses the syntax:

Decorator syntax in Chrome (an error on purpose)Pop out in the code editor (opens in a new tab)JavaScript
class TeaCup extends HTMLElement {
  @attribute({ type: Number })
  accessor size;
}

It throws a SyntaxError before it runs. So TypeScript or Babel turns decorators into plain JavaScript first. The playground runs what TypeScript made from tea-cup.ts, with three settings:

Playground: what TypeScript makes of the decorators
A cup built from compiled tea-cup.tsPop out in the code editor (opens in a new tab)HTML
<p><tea-cup size="4" roast="dark">Hojicha</tea-cup></p><script type="module">  import { TeaCup } from "./tea-cup.js";  const cup = document.querySelector("tea-cup");  console.log(`TeaCup watches: ${TeaCup.observedAttributes.join(", ")}`);  cup.size = 5;  console.log(`size="${cup.getAttribute("size")}"`);</script>
ResultLoading…
Try it yourself
@attribute() on an accessor

TypeScript calls attribute() with a context object. It keeps the declaration in the class's metadata, and finalize() reads it there.

Only the tea-cup.js tab changes: TypeScript's output for each setting.
  • Line 1 is a cup with a size of 4 and a dark roast.
  • Line 5 prints what the class watches. Lines 6 and 7 set the size to 5, and print the attribute.

Standard decorators print TeaCup watches: size, roast and size="5". So do legacy ones with useDefineForClassFields: false. Legacy with true prints size="4" and the class field error. TypeScript kept size; and roast; as fields. That's why Lit asks for false with legacy decorators.

Open the first choice's tea-cup.js tab. It's long: TypeScript adds two helpers, __esDecorate and __runInitializers. Lit gives that size as the reason it still recommends TypeScript's legacy decorators (Lit). In Lit itself, the cup's size reads like this:

The cup's size in Lit, with a standard decoratorTypeScript
import { LitElement } from "lit";
import { property } from "lit/decorators.js";

class TeaCup extends LitElement {
  @property({ type: Number, reflect: true, useDefault: true })
  accessor size = 3;
}
  • Line 5 makes a number that reflects. useDefault keeps the default from becoming an attribute.
  • Line 6 is an auto-accessor with a starting value. Lit reads that 3 as the default.

Lit 3 was the first Lit to take standard decorators. Older examples, written for legacy decorators, put @property() on a plain field. With standard decorators, they need accessor added (Lit 3 upgrade guide). Lit uses them in full.

How do Lit and Catalyst declare attributes?

The same jobs, done three ways. Read each row across:

Declaring one attribute in three toolkits
QuestionTeaElementLitCatalyst 1.8
Where do you declare it?In static attributes, or with @attribute().In static properties, or with @property().With @attr on a class field.
What is the attribute called?The name with dashes: giftWrapped watches gift-wrapped.The name in lowercase: giftWrapped watches giftwrapped.data- and the name with dashes: data-gift-wrapped.
Where does the value live?In a private Map on each element.Under a hidden symbol key on each element.In the attribute itself.
What does size="big" give for a number?The fallback, by HTML's rules.NaN, from Number().NaN, from Number().
When is the attribute written?In the setter, before it returns.In the next update, a microtask later.Always, because the attribute holds the value.
What about a class field with the same name?It throws on connection.Its development build throws at the first update.It puts its property on each element, on top of the field.

Lit

  • defaultConverter reads a Number with Number(), a Boolean by presence, and objects and arrays with JSON.parse() (lines 353 to 393). notEqual compares with Object.is() (lines 403 and 404).
  • By default, a property is a String with an attribute, and doesn't reflect (lines 406 to 413). The attribute is the name in lowercase (lines 975 to 987).
  • createProperty() puts the accessor on the prototype (lines 698 to 725). getPropertyDescriptor() builds it: the setter stores the value and asks for an update (lines 754 to 794).
  • Reflection waits for update() (lines 1655 to 1662), a microtask after the set.

GitHub's Catalyst

  • @attr is a legacy decorator that only records the name (lines 15 to 17).
  • When an element connects (core.ts, lines 54 to 58), initializeAttrs() reads each field's starting value. Its type picks a string, number, or boolean property (lines 39 to 83).
  • It defines that property on the element itself, on top of the field (line 78). It writes the starting value into the attribute when the page left it out (lines 79 to 81).
  • Names get a data- prefix and dashes (line 43 and line 47).

Each choice has a reason. Catalyst's attribute is the only place the value lives, so nothing can drift. Lit keeps values as given and reflects once per update. TeaElement copies built-in elements: bad text falls back, and the attribute is written at once.

Adding declared attributes to the tea kit

The kit gets declared attributes in kitAfter192:

  • tea-kit/element.js: TeaElement, as this lesson built it, with comments.
  • tea-kit/converters.js (new helper): converterFor().
  • tea-kit/tea-cup.js (new): the cup, with the kit's tokens and layers.
  • tea-kit/tea-price.js: two declared attributes in place of four hand-written accessors.
  • tea-kit/custom-elements.json: the new members of element.js, and the two new modules.

Here is the price now:

tea-kit/tea-price.js with declared attributesJavaScript
import { TeaElement } from "./element.js";

export class TeaPrice extends TeaElement {
  static attributes = {
    amount: { reflect: true },
    currency: { reflect: true },
  };

  createRenderRoot() {
    return this;
  }

  render() {
    const currency = this.currency ?? "";
    this.textContent = `Price: ${this.amount} ${currency}`.trim();
  }
}

customElements.define("tea-price", TeaPrice);
  • Lines 4 to 7 declare amount and currency, as text that reflects. They replace lesson 19.1's four accessors.
  • Line 15 reads them through the generated properties.

Why text, and not a Number? A price like 4.50 keeps its zero as text. As a number, it would come back as 4.5. Now both together:

The kit's cup and price, with typed propertiesPop out in the code editor (opens in a new tab)HTML
<link rel="stylesheet" href="tea-kit/tokens.css"><p><tea-cup size="4" roast="dark">Hojicha</tea-cup> <tea-price amount="4.50" currency="EUR"></tea-price></p><script type="module">  import "./tea-kit/index.js";  const cup = document.querySelector("tea-cup");  const price = document.querySelector("tea-price");  console.log(`cup.size: ${cup.size}, a ${typeof cup.size}`);  console.log(`price.amount: ${price.amount}, a ${typeof price.amount}`);</script>
ResultLoading…

Lines 7 and 8 print cup.size: 4, a number and price.amount: 4.50, a string. The price shows the same text as before, and keeps a value set before the kit loads. One change for kit authors: only declared attributes get that early-value treatment now. Declare an attribute if code may set its property early.

Common mix-ups

  • "attributeChangedCallback() runs for every attribute." No. It runs only for names in observedAttributes, which TeaElement builds from the declarations.
  • "iced="false" turns a boolean attribute off." No. Any text means on. Remove the attribute, or set the property to false.
  • "Reflect every property, so the HTML shows the state." No. Each change writes the HTML and runs the callback. Reflect settings and styling hooks, and use :state() for internal state.
  • "A class field is a fine place for a default." No. It hides the generated property. Give the default as fallback.
  • "Decorators run in browsers now." No. They're a stage 2.7 proposal, Chrome throws a SyntaxError, and TypeScript or Babel compiles them.
  • "Examples for legacy decorators work with standard ones." No. Standard decorators need accessor on the field.
  • "Lit's Number converter gives a default for bad text." No. It uses Number(), so big gives NaN.
  • "Only objects and dates need the reflection guard." No. TeaElement's setter writes the attribute every time, so even a number loops without it.

Practice exercises

Exercise 1 · Warm-upPredict a size and a roast

The cup says size="2.5 cups" and roast="DARK". Predict what the page prints, then run it.

<tea-cup size="2.5 cups" roast="DARK">Oolong</tea-cup><script type="module">  import "./tea-cup.js";  const cup = document.querySelector("tea-cup");  console.log(cup.size, cup.roast);</script>
ResultLoading…

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · Warm-upPredict a boolean that says false

    The cup says iced="false". Then the script sets cup.iced = false. What does the page print?

    <tea-cup iced="false">Sencha</tea-cup><script type="module">  import "./tea-cup.js";  const cup = document.querySelector("tea-cup");  const before = cup.iced;  cup.iced = false;  console.log(before, cup.iced, cup.hasAttribute("iced"));</script>
    ResultLoading…

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeDeclare an order's attributes

      Fill in static attributes in the tea-order.js tab. Then press One more sugar once. What does the order show?

      <p><tea-order strength="STRONG" sugar="two">Chai</tea-order></p><button id="sugar">One more sugar</button><script type="module">  import "./tea-order.js";  const order = document.querySelector("tea-order");  document.querySelector("#sugar").addEventListener("click", () => {    order.sugar += 1;  });</script>
      ResultLoading…

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeFix the cup that stays iced

        Press Not iced. The cup still says iced, and the page reports an error. Fix the tea-cup.js tab. What does the cup show after the press then?

        <p><tea-cup iced size="2">Matcha</tea-cup></p><button id="warm">Not iced</button><script type="module">  import "./tea-cup.js";  const cup = document.querySelector("tea-cup");  document.querySelector("#warm").addEventListener("click", () => {    cup.iced = false;  });</script>
        ResultLoading…

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeWrite a converter for a list of flavors

          The tasting cup's converter in the tasting-cup.js tab hands text through as it is. Make flavors a list of words, like the class attribute. What does the page print after one press of Add sweet?

          <p><tasting-cup flavors="malty  smoky">Assam</tasting-cup></p><button id="sweet">Add sweet</button><script type="module">  import "./tasting-cup.js";  const cup = document.querySelector("tasting-cup");  console.log(`${cup.flavors.length} flavors`);  document.querySelector("#sweet").addEventListener("click", () => {    cup.flavors = [...cup.flavors, "sweet"];    console.log(cup.getAttribute("flavors"));  });</script>
          ResultLoading…

          Answer, then press Check. Spacing and letter case don’t matter.

            Exercise 6 · ChallengeGive numbers a max option

            The cup declares max: 5 for size, and says size="9". Add the option to the converters.js tab, so a bigger number counts as the max. What does the page print?

            <p><tea-cup size="9">Sencha</tea-cup></p><script type="module">  import "./tea-cup.js";  console.log(document.querySelector("tea-cup").size);</script>
            ResultLoading…

            Answer, then press Check. Spacing and letter case don’t matter.

              Check your understanding

              The declared attributes quiz · 7 questionsScore: first tries count
              1. Question 1 of 7A page has 50 cups. Where does TeaElement put the getter and setter for size?

                Choose an answer to see the explanation.

              2. Question 2 of 7The page holds <tea-cup size="big">. What does this code print?

                Read the code, then predictJavaScript
                const cup = document.querySelector("tea-cup"); // <tea-cup size="big">
                console.log(cup.size, cup.getAttribute("size"));

                Choose an answer to see the explanation.

              3. Question 3 of 7In what order does this code print its letters?

                Read the code, then predictJavaScript
                class TeaTimer extends HTMLElement {
                  static observedAttributes = ["seconds"];
                  attributeChangedCallback() {
                    console.log("b");
                  }
                }
                customElements.define("tea-timer", TeaTimer);
                const timer = document.createElement("tea-timer");
                console.log("a");
                timer.setAttribute("seconds", "60");
                console.log("c");

                Choose an answer to see the explanation.

              4. Question 4 of 7Why does TeaElement's #reflecting check stop the reflection loop?

                Choose an answer to see the explanation.

              5. Question 5 of 7A TeaCup subclass writes size = 2; as a class field. What happens?

                Choose an answer to see the explanation.

              6. Question 6 of 7Can Chrome run @attribute({ type: Number }) accessor size; with no build step?

                Choose an answer to see the explanation.

              7. Question 7 of 7Which of these should a tea cup NOT reflect to an attribute?

                Choose an answer to see the explanation.

              Key takeaways

              • Declare each attribute once, with its type, its default, and whether it reflects.
              • finalize() turns the declarations into observedAttributes, a map by attribute name, and one property each.
              • createProperty() puts a getter and a setter on the prototype. Each element keeps its values in a private Map.
              • A class field hides a generated property. Give defaults as fallback instead.
              • Converters read text with HTML's rules and a fallback. A setter sends values through the same rules.
              • The callback runs inside setAttribute(), so one #reflecting mark stops the loop both ways.
              • Bad text gives the default, the attribute keeps its text, and a default never becomes an attribute.
              • Decorators declare the same thing, but need TypeScript or Babel: no browser runs them yet.

              Remember the one-liner.
              Say what each attribute is once, and let the base class keep the property and the attribute in step.

              Sources

              The facts on this page come from these docs, posts, specifications, and source files:

              Support data comes from MDN's browser-compat-data.

              Coming next: Mixins, controllers, and behaviors. Share behavior between components without deep inheritance.

              CompleteFrontend Clear concepts. Working examples.