completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

Properties set before the upgrade

A custom element property set before the upgrade hides your setter. Learn why, the upgrade-property pattern that fixes it, and how to test for it.

By the end, you can
  • 01
    Explain why the setter doesn't runA property set on a waiting element becomes its own property, and that hides the class's setter after the upgrade.
  • 02
    Fix it with the upgrade-property patternRead the value, delete the own property, and set it again, in connectedCallback(), for each public property.
  • 03
    Test for itWrite a test that sets a property before define() and checks what the element shows afterwards.

Why doesn't my custom element's setter run?

Ravi is building the cart page for Leaf and Kettle. His script finds each <tea-price> and sets its amount with price.amount = 4. The tea kit loads from its own file. On his laptop, the kit is already cached and arrives first, so the prices show up. On Asha's slow phone, the kit arrives after his script. The prices stay blank, and the console shows no error.

Why does the same line work on one device and not on the other? And why does the price stay blank even when Ravi sets it again later?

A property set on a custom element before its class loads becomes the element's own property. The upgrade keeps it, and it sits in front of your class's setter, so the setter never runs. The fix is the upgrade-property pattern. When the element connects, read its own property, delete it, and set the value again, so it goes through the setter.

Here is the problem on its own. The page sets the amount first, then loads the class:

A price whose amount is set before its class loadsPop out in the code editor (opens in a new tab)HTML
<p>Green tea. <tea-price></tea-price></p> <script type="module">  const price = document.querySelector("tea-price");  price.amount = 4;  await import("./tea-price.js");  console.log("Own property:", Object.hasOwn(price, "amount"));</script>
ResultLoading…
  • Line 1 is a paragraph with a <tea-price> in it. Nothing has defined tea-price yet, so it waits.
  • Line 4 finds the price. Line 5 sets its amount to 4.
  • Line 6 loads tea-price.js, the second tab, with import(). That file's last line defines tea-price, so the waiting price upgrades.
  • In the tea-price.js tab, lines 8 to 12 are a setter: a function that runs when code sets amount. It logs Setter ran with and the value, then writes the price.
  • Line 7 asks if the price has its own amount property.

The result shows only Green tea.. The console prints Own property: true, and nothing else. Setter ran with 4 never appears. The 4 is on the element, but it never reached the setter.

Here is the whole story in one picture. The rest of the lesson takes it apart, row by row:

The early amount's story in three rows. Before the class loads, price.amount = 4 makes an own amount of 4, kept on the element. During the upgrade, define() brings the class's setter, set amount(), but the own amount hides it. With the upgrade-property pattern, connectedCallback() reads, deletes, and sets the value again, and the price shows Price: 4.Before the class loadsprice.amount = 4own amount: 4kept on the elementThe upgradedefine()set amount()the setter arrives,but the own amount hides itWith the upgrade-property patternconnectedCallback()read, delete, setPrice: 4
The early 4 waits on the element itself. The upgrade brings the setter, but the own amount hides it. The pattern hands the 4 over when the element connects.
Real-life analogyA note stuck over the thermostat

Asha writes "21 degrees" on a sticky note. She sticks it on the wall where the new thermostat will go. The installer fits the thermostat right over that spot, and the note ends up stuck on its front. Everyone who walks past reads the note. Some write a new number on it. Nobody turns the real dial, so the heating never changes.

In real life: The bare wall, before the thermostat
In JavaScript: The waiting element, with no amount setter
In real life: The note saying 21
In JavaScript: The own property amount: 4
In real life: The thermostat's real dial
In JavaScript: The class's setter, on its prototype
In real life: Writing a new number on the note
In JavaScript: A later price.amount = 5
In real life: The heating that never changes
In JavaScript: The price that stays blank
The main idea

An early property hides your setter. Before the upgrade, price.amount = 4 stores the value on the element itself. After the upgrade, JavaScript finds that own property first, so your setter never runs. Your class has to move the value to the setter.

Lesson 2.2 met this bug from the page's side, and fixed it by waiting for the class. Lesson 4.1 showed that an upgrade keeps the same element. This lesson looks from your side, as the author of the class. Why does the value stay on the element, and how can your class pick it up?

What happens to a property set before the upgrade?

Follow the 4 step by step. Before the upgrade, the price is a plain HTMLElement. Nothing in its prototype chain has an amount. When you set a property that an object doesn't have, JavaScript adds it to the object itself. That's an own property: one stored on the object, not on its prototype.

Then the upgrade comes. The browser gives the element your class's prototype, the object that holds your getter and setter. It changes nothing else. The HTML Standard's steps for HTML element constructors spell this out. The super() call changes the element's prototype, then hands back the same element. So the own amount is still there. This page checks it before and after:

Where the early amount lives, before and afterPop out in the code editor (opens in a new tab)HTML
<tea-price></tea-price> <script type="module">  const price = document.querySelector("tea-price");  price.amount = 4;  console.log("Own before:", Object.hasOwn(price, "amount"));   const { TeaPrice } = await import("./tea-price.js");  console.log("Own after:", Object.hasOwn(price, "amount"));   const own = Object.getOwnPropertyDescriptor(price, "amount");  const shared = Object.getOwnPropertyDescriptor(TeaPrice.prototype, "amount");  console.log("On the element:", Object.keys(own).join(", "));  console.log("On the class:", Object.keys(shared).join(", "));</script>
ResultLoading…
  • Line 5 sets the amount on the waiting price. Line 6 prints Own before: true.
  • Line 8 loads the class and keeps it in TeaPrice. Line 9 prints Own after: true.
  • Line 11 asks how the element stores amount. Object.getOwnPropertyDescriptor() gives an object that describes one own property. Line 12 asks the same of the class's prototype.
  • Line 13 prints On the element: value, writable, enumerable, configurable. A value means a plain value. This is a data property.
  • Line 14 prints On the class: get, set, enumerable, configurable. A get and a set mean an accessor: a getter and a setter.

So the price now has two amounts. Its own plain value sits on the element. The class's accessor sits one step down the chain. When you read or set price.amount, JavaScript looks at the element first. It finds the own amount there and stops. The prototype chain lesson calls this shadowing: the own property hides the one below it. The Getters & setters lesson shows why a class's accessors live on its prototype.

Setting price.amount after the upgrade. An arrow from price.amount = 5 points left to an own amount card in the price element, marked found here first. Below, an arrow goes to the element's prototype, TeaPrice.prototype, which holds get amount() and set amount(). The setter is crossed out and marked never runs.amount: 5pricefound here firstprice.amount = 5its prototypeprototypeget amount()set amount()never runsTeaPrice.prototype
JavaScript looks on the element first. It finds the own amount and stops there, so the setter on TeaPrice.prototype never runs.

Every later set misses the setter too

The early value isn't the only one that's lost. Set the amount again after the upgrade:

Setting the amount again after the upgradePop out in the code editor (opens in a new tab)HTML
<p>Green tea. <tea-price></tea-price></p> <script type="module">  const price = document.querySelector("tea-price");  price.amount = 4;  await import("./tea-price.js");  price.amount = 5;  console.log("amount:", price.amount, "text:", price.textContent || "none");</script>
ResultLoading…
  • Line 5 sets 4 early. Line 6 loads the class, and the price upgrades.
  • Line 7 sets 5, after the class has loaded.
  • Line 8 prints amount: 5 text: none.

The 5 landed on the own property too. The price stays blank, and Setter ran with never prints. Why it matters: this element stays broken for as long as it lives, not just for one value. That's why Ravi's prices stayed blank when he set them again.

Names every element already has

Some names have a setter on every element already. hidden, title, and id are examples. HTMLElement defines them on its prototype. So setting one of them early runs that built-in setter at once:

A built-in property and a new one, set earlyPop out in the code editor (opens in a new tab)JavaScript
const price = document.createElement("tea-price");
price.hidden = true;
price.amount = 4;

console.log("hidden is own:", Object.hasOwn(price, "hidden"));
console.log("hidden attribute:", price.hasAttribute("hidden"));
console.log("amount is own:", Object.hasOwn(price, "amount"));
  • Line 1 makes a tea-price. It waits, because nothing defines it here.
  • Line 2 sets hidden. Line 3 sets amount.
  • Lines 5 and 6 print hidden is own: false and hidden attribute: true.
  • Line 7 prints amount is own: true.

The built-in setter turned hidden into an attribute, with no own property. Only amount became an own property, because the plain element doesn't know that name. So the problem hits exactly the properties your class adds. Chrome's custom elements guidance also warns you not to reuse built-in names like title or id for your own properties.

Can a class field hide a setter too?

Yes. A class field is a property you declare in the class body, like amount = 0;. JavaScript adds it to each new element as an own property, right after super() returns. If the field has your setter's name, it hides the setter on every element, early or not:

A field with the same name as the setterPop out in the code editor (opens in a new tab)JavaScript
class TeaPrice extends HTMLElement {
  amount = 0;

  set amount(value) {
    console.log("Setter ran with", value);
  }
}
customElements.define("tea-price", TeaPrice);

const price = new TeaPrice();
price.amount = 4;
console.log("Own property:", Object.hasOwn(price, "amount"));
  • Line 2 is a field. It looks like a default amount.
  • Lines 4 to 6 are the setter.
  • Line 10 makes a price after define(), so nothing was set early.
  • Line 11 sets the amount. Line 12 prints Own property: true.

Setter ran with 4 never prints. The field made the same own property that an early set makes. Lit's docs warn about this mistake in avoiding issues with class fields. While you develop, Lit even throws an error when it finds one.

The fix is to store the value under another name. That's why TeaPrice keeps its value in #amount. A name that starts with # is a private field. Only code inside the class can use it, and it can't clash with amount. To give a default, write #amount = 0;.

Why it matters: a field with a setter's name breaks every element, not just the early ones. If a setter never runs, even on elements made after define(), look for a field with the same name.

How does the upgrade-property pattern work?

Your class can't stop a page from setting a property early. But it can clean up afterwards. When the element connects, the class checks for an own property. If it finds one, it moves the value to the setter in three steps:

  1. Read the value, and keep it in a variable.
  2. Delete the own property. The delete operator removes a property from the object itself. It never touches the prototype, so the setter is in reach again.
  3. Set the value again. This time it goes through the setter.

web.dev's custom element checklist calls this making properties lazy, and names its helper _upgradeProperty(). Here is the same fix in tea-price.js. The page is the overview's page, unchanged:

The same early page, with the pattern in the classPop out in the code editor (opens in a new tab)HTML
<p>Green tea. <tea-price></tea-price></p> <script type="module">  const price = document.querySelector("tea-price");  price.amount = 4;  await import("./tea-price.js");  console.log("Own property:", Object.hasOwn(price, "amount"));</script>
ResultLoading…
  • Only the tea-price.js tab changed. Its lines 14 to 20 are new: a connectedCallback().
  • connectedCallback() runs when the price joins a page. It also runs during the upgrade, when the price is on the page already.
  • Line 15 asks if this element has its own amount. Object.hasOwn() answers that question.
  • Line 16 reads the own value, 4, into value.
  • Line 17 deletes the own property.
  • Line 18 sets 4 again. Now JavaScript finds the setter on the prototype.

The console prints Setter ran with 4, then Own property: false. The result shows Green tea. Price: 4.

The pattern's three steps, left to right. Step 1, read: value = 4 saves the value. Step 2, delete: the own amount is removed, which uncovers the setter. Step 3, set again: set amount(4) runs, and an arrow leads down to the price showing Price: 4.1. Read2. Delete3. Set againvalue = 4own amountset amount(4)saves the valueuncovers the setterPrice: 4the setter draws it
Read first, so the 4 is safe. Delete next, so the setter is in reach. Set last, so the 4 goes through the setter.
Real-life analogyA parcel left on the doorstep

A parcel arrives at the new tea shop before it opens. Nobody is at the counter, so the courier leaves it on the doorstep. On her first morning, the owner picks it up, clears the step, and books the parcel in at the counter. From then on, couriers bring parcels to the counter.

In real life: The parcel on the doorstep
In JavaScript: The own property amount: 4
In real life: Picking up the parcel
In JavaScript: const value = this.amount
In real life: Clearing the step
In JavaScript: delete this.amount
In real life: Booking it in at the counter
In JavaScript: this.amount = value, through the setter
In real life: Later parcels going to the counter
In JavaScript: Later sets running the setter

Why the order matters

The three steps only work in this order. Try the other two:

Playground: put the three steps in order
The early page, with the pattern's steps in one orderPop out in the code editor (opens in a new tab)HTML
<p>Green tea. <tea-price></tea-price></p> <script type="module">  const price = document.querySelector("tea-price");  price.amount = 4;  await import("./tea-price.js");  console.log("Own property:", Object.hasOwn(price, "amount"));</script>
ResultLoading…
Try it yourself
The value reaches the setter.

Line 16 saves 4. Line 17 deletes the own property, so the class's setter is in reach again. Line 18 sets 4 through it, and the price shows Price: 4.

Each choice is the same page. Only lines 16 to 18 in the tea-price.js tab change. Each run starts in a fresh page.

With Delete, then read, line 16 deletes the 4 before anything saved it. Line 17 reads through the getter, which has nothing yet. So the setter runs with undefined, and the price shows Price: undefined.

With Set, then delete, line 17 sets the value while the own property is still there. So it lands on the own property, and the setter doesn't run. Line 18 then throws it away. No price shows.

Why it matters: read first, so the value is safe. Delete next, so the setter is in reach. Set last, so the value goes through it.

web.dev and Lit make the check on line 15 with this.hasOwnProperty(name). For an element, it gives the same answer as Object.hasOwn(this, name). The prototype chain lesson compares the two in its checking tools.

Where should the upgrade-property pattern run?

web.dev runs the pattern in connectedCallback(). Its sample checkbox, howto-checkbox, does it there for checked and disabled. Nolan Lawson's post on custom element upgrades runs it in the constructor. Both catch the early value during an upgrade. So which should you pick?

Look at what your setter does. Lesson 3.2 says a constructor must not add attributes or children. TeaPrice's setter writes text, and text is a child. So its pattern belongs in connectedCallback(). A setter that only stores the value in a private field could run in the constructor.

connectedCallback() runs each time the element joins a page. After the first time, no own property is left. So line 15's check is false, and the pattern does nothing.

There's one case to know. An element can upgrade off the page, with customElements.upgrade() from lesson 4.1. Its constructor runs, but connectedCallback() waits until it joins a page. Until then, the own property still hides the setter. Exercise 6 tries this.

Which properties need it?

Run the pattern for each property that a user of your component might set: every public property with a setter. You don't need it for these:

  • Private fields, like #amount. Code outside the class can't set them.
  • Names every element already has, like hidden. They never become own properties.

With more than one property, a small helper takes the name. The tea kit uses this one, in the practical below:

A helper that runs the pattern for each property (part of a class)JavaScript
connectedCallback() {
  for (const name of ["amount", "currency"]) this.#upgradeProperty(name);
  this.#render();
}

#upgradeProperty(name) {
  if (!Object.hasOwn(this, name)) return;
  const value = this[name];
  delete this[name];
  this[name] = value;
}
  • Line 2 runs the helper once for each name. Line 3 draws the price after that.
  • Line 7 stops early when the element has no own property with that name.
  • Lines 8 to 10 are the three steps. They write this[name] instead of this.amount. The square brackets read the property whose name is in name.

The # before upgradeProperty makes it a private method, so pages can't call it. Why it matters: forget a name in the list on line 2, and that one property breaks. Exercise 4 is about this mistake.

Does Lit handle properties set before the upgrade?

Yes. Lit's docs list it among the things Lit manages for you. If an element is defined after it's already on the page, properties set before the upgrade still take effect. In lesson 2.2, setting open early on a Web Awesome element worked for this reason. Web Awesome is built with Lit.

Lit's base class, ReactiveElement, does it in two steps. First, its constructor calls a method that saves every early value. Here it is, from Lit's source:

__saveInstanceProperties(), from reactive-element.ts at lit@3.3.3TypeScript
private __saveInstanceProperties() {
  const instanceProperties = new Map<PropertyKey, unknown>();
  const elementProperties = (this.constructor as typeof ReactiveElement)
    .elementProperties;
  for (const p of elementProperties.keys() as IterableIterator<keyof this>) {
    if (this.hasOwnProperty(p)) {
      instanceProperties.set(p, this[p]);
      delete this[p];
    }
  }
  if (instanceProperties.size > 0) {
    this.__instanceProperties = instanceProperties;
  }
}
  • Line 2 makes a Map, a list of keys and their values.
  • Lines 3 and 4 get the reactive properties the class declares.
  • Line 6 checks each one with hasOwnProperty, like line 15 of the fixed tea-price.js.
  • Line 7 saves the value in the map. Line 8 deletes the own property.
  • Line 12 keeps the map on the element for later.

The second step comes at Lit's first update, after the element connects. A short loop sets each saved value through its accessor. So Lit runs your pattern's three steps: read, delete, and set. It just waits between the delete and the set.

How Lit handles an early property. On the left, an own amount of 4, set before the upgrade. An arrow leads to a crate labelled Map holding amount: 4, saved by the constructor. Another arrow leads to set amount(4), which runs at the first update.own amount: 4amount: 4Mapset amount(4)set before the upgradesaved by the constructorset at the first update
Lit's constructor moves each early value into a Map and deletes the own property. Its first update sets each one through the setter.
Real-life analogyA hotel desk that holds early letters

Letters arrive at a hotel before the guest checks in. The front desk doesn't leave them in the corridor. It keeps them in a pigeonhole. When the guest checks in, the clerk hands every letter over.

In real life: Letters that arrive before the guest
In JavaScript: Properties set before the upgrade
In real life: The pigeonhole at the desk
In JavaScript: Lit's Map of saved values
In real life: Taking them in from the corridor
In JavaScript: delete this[p] in the constructor
In real life: Handing them over at check-in
In JavaScript: Setting each one at the first update

Which code sets properties early?

Early properties come from code that runs before your class loads. A plain script can do it, like Ravi's. So can frameworks that set properties for you:

  • Angular's property binding, like [amount]="price". web.dev's lazy properties section shows this case with a checkbox's [checked].
  • Lit's property binding, .amount=${price}, which always sets the property, as Jake Archibald explains.

Other frameworks check first. React 19's code for custom elements sets a property only if "amount" in element is true. Jake Archibald's post shows Preact and Vue doing the same check. Before the upgrade, a waiting element has no amount, so they set an attribute instead.

An observed attribute is safe. The upgrade calls attributeChangedCallback() for it, as lesson 3.4 showed. But an object set as an attribute turns into the text [object Object].

Why it matters: if your component takes properties, expect some page to set them early. Add the pattern, or build on a library that has it.

How do you test for properties set before the upgrade?

A normal test loads the component first, then makes an element. That never catches this bug, because nothing is set early. A test for it copies the bad order on purpose. It makes the element, sets the property, and only then loads the class.

Real-life analogyA fire drill

A café doesn't wait for a real fire to check its exits. On a quiet morning, it sets off the alarm on purpose and watches everyone walk out. If an exit is blocked, they clear it before it matters.

In real life: Setting off the alarm on purpose
In JavaScript: Setting the property before define() in a test
In real life: Watching everyone walk out
In JavaScript: Checking what the element shows
In real life: Clearing a blocked exit
In JavaScript: Adding the upgrade-property pattern

Run this test page against both versions of the class:

Playground: run the test against both classes
A test for a property set before define()Pop out in the code editor (opens in a new tab)HTML
<script type="module">  const price = document.createElement("tea-price");  price.amount = 4;  document.body.append(price);  await import("./tea-price.js");   const check = (name, passed) => console.log(passed ? "PASS" : "FAIL", name);  check("shows the amount set before define()", price.textContent === "Price: 4");  price.amount = 5;  check("runs the setter after the upgrade", price.textContent === "Price: 5");</script>
ResultLoading…
Try it yourself
Both checks fail.

Line 3 made an own property, so the setter never runs: not for the 4, and not for the 5 on line 9. The price stays empty.

The test page stays the same. Only the tea-price.js tab changes: the hand-written class, or the one with the pattern.
  • Line 2 makes a price. tea-price isn't defined yet, so it waits.
  • Line 3 sets the amount early. Line 4 adds the price to the page.
  • Line 5 loads the class. It defines tea-price, and the price upgrades.
  • Line 7 is a tiny helper. It prints PASS or FAIL, then the check's name.
  • Line 8 checks the early value. Lines 9 and 10 set a new amount, and check that the setter ran.

Against the class without the pattern, both checks print FAIL. Against the class with it, both print PASS, each after a Setter ran with line. The second check matters too. It proves that no own property is left to hide later sets.

When the class is already loaded

Say your test file imports the component at the top. Then tea-price is defined before any test runs, so you can't make a waiting one. Use a new tag name instead. Set the property, then define a small subclass under that name:

A fresh tag name for a class that is already loadedPop out in the code editor (opens in a new tab)HTML
<script type="module">  import { TeaPrice } from "./tea-price.js";   const price = document.createElement("late-price");  price.amount = 4;  document.body.append(price);  customElements.define("late-price", class extends TeaPrice {});  console.log(price.textContent === "Price: 4" ? "PASS" : "FAIL");</script>
ResultLoading…
  • Line 2 imports the class. That defines tea-price at once.
  • Line 4 makes a late-price. Nothing defines that name yet, so it waits.
  • Line 5 sets the amount early. Line 6 adds the price to the page.
  • Line 7 defines late-price as an empty subclass of TeaPrice. The waiting price upgrades, and runs TeaPrice's code.
  • Line 8 prints PASS.

Put the class without the pattern in the tab, and line 8 prints FAIL. The empty subclass is a new class, so the registry takes it under a new name. In lesson 4.1, the same class under two names threw an error. So give each test its own name. Stage 11 puts tests like these in a real test runner.

Adding the pattern to the tea kit

Back to Ravi's cart. His script sets the price's amount and currency, and the kit loads after it. Until now, the kit's tea-price only read attributes. In this lesson's version of the kit, it gets two properties and the pattern:

The cart sets the kit's price before the kit loadsPop out in the code editor (opens in a new tab)HTML
<p>Green tea. <tea-price></tea-price></p> <script type="module">  const price = document.querySelector("tea-price");  price.amount = 4;  price.currency = "EUR";  await import("./tea-kit/index.js");  console.log(price.textContent);  console.log(price.getAttribute("amount"), Object.hasOwn(price, "amount"));</script>
ResultLoading…

Open the tea-kit/tea-price.js tab:

  • Lines 4 to 10 are the amount property. The getter reads the attribute, and the setter writes it. Lines 12 to 18 do the same for currency. Chrome's guidance shows properties like these.
  • Writing the attribute calls attributeChangedCallback(), on lines 25 to 28. It draws the price again, as in lesson 3.4.
  • Line 21 runs the pattern for both names. Line 22 then draws the price.
  • Lines 30 to 35 are the helper from the last section.

In the index.html tab, lines 5 and 6 set both properties early. Line 7 loads the whole kit. Line 8 prints Price: 4 EUR. Line 9 prints 4 false: the setter wrote the attribute, and no own property is left. The result shows Green tea. Price: 4 EUR.

With the kit from lesson 3.5, the same page shows Green tea. Price: null. That kit had no amount property, so the early values stayed own properties, and nothing wrote the attribute.

Why it matters: now anything that sets the kit's price works, whenever the kit arrives. A framework that sets an attribute instead works too, because tea-price observes it.

Common mix-ups

Read each row from left to right: what a page does before the upgrade, what happens to it, and what to do about it.

What a page can do to a waiting element
What does the page do before the upgrade?What happens to it?What should you do about it?
It writes an attribute, like amount="4" or setAttribute("amount", 4).It stays on the element. The upgrade calls attributeChangedCallback() for it, if the class observes it.Nothing more. Lesson 3.4 covers it.
It sets a property the class defines, like price.amount = 4.It becomes the element's own property. It hides the setter, for that value and every later one.It needs the upgrade-property pattern.
It sets a property every element has, like price.hidden = true.HTMLElement's own setter runs at once. No own property is made.It needs nothing.
It calls a method, like lesson 2.2's details.show().It throws a TypeError, because the method doesn't exist yet.Wait with whenDefined() first, as lesson 2.2 shows.
  • "The upgrade throws away anything set before it." No. The upgrade keeps the same element, with everything on it. An early property stays, as an own property in front of the setter.
  • "Only the first value is lost." No. Every later set lands on the own property too. The setter never runs for that element, until something deletes the own property.
  • "'amount' in price tells you if it was set early." No. in looks down the prototype chain too, so after the upgrade it's always true. Use Object.hasOwn().
  • "Early attributes need the pattern too." No. Attributes are part of the element. The upgrade calls attributeChangedCallback() for each observed one.
  • "A class field is just a default value." No. A field with a setter's name makes an own property on every element, so the setter never runs. Keep the value in a private field.
  • "Lit components need the pattern too." No. Lit's ReactiveElement saves early values in its constructor and sets them at its first update.

Practice exercises

Answer first, then use the hints. Each result runs live, so you can check yourself.

Exercise 1 · Warm-upTwo early sets

This page uses the fixed tea-price.js. Lines 5 and 6 both set the amount before the class loads. How many times does the setter run?

<p>Green tea. <tea-price></tea-price></p> <script type="module">  const price = document.querySelector("tea-price");  price.amount = 3;  price.amount = 4;  await import("./tea-price.js");</script>
ResultLoading…

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

    Exercise 2 · Warm-upA built-in name and a new one

    What does line 5 print?

    Starter codePop out in the code editor (opens in a new tab)JavaScript
    const price = document.createElement("tea-price");
    price.title = "Our price";
    price.amount = 3;
    
    console.log(Object.hasOwn(price, "title"), Object.hasOwn(price, "amount"));

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

      Exercise 3 · PracticeAdd the pattern to a label

      The page sets the label's name before its class loads, so the label just shows Mint tea. Add the pattern to the tea-label.js tab. What does the label show then?

      <tea-label>Mint tea</tea-label> <script type="module">  const label = document.querySelector("tea-label");  label.name = "Mint tea";  await import("./tea-label.js");</script>
      ResultLoading…

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

        Exercise 4 · PracticeThe missing currency

        This copy of the kit has a bug in tea-kit/tea-price.js. The price shows no currency. Find the bug and fix it. What does line 8 print then?

        <p>Green tea. <tea-price></tea-price></p> <script type="module">  const price = document.querySelector("tea-price");  price.amount = 4;  price.currency = "EUR";  await import("./tea-kit/index.js");  console.log(price.textContent);  console.log(price.getAttribute("amount"), Object.hasOwn(price, "amount"));</script>
        ResultLoading…

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

          Exercise 5 · ChallengeWrite the test for the label

          The tea-label.js tab holds the label from exercise 3, with the pattern. Write a test that sets the name before the class loads, then prints PASS or FAIL. What does it print?

          <script type="module">  // 1. Make a tea-label and set its name to "Mint tea".  // 2. Add it to the page, then load ./tea-label.js.  // 3. Print PASS if it shows "Mint tea: brew for 3 minutes", or FAIL.</script>
          ResultLoading…

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

            Exercise 6 · ChallengeA price upgraded off the page

            The fixed tea-price.js is in the tab. What does line 6 print?

            <script type="module">  const price = document.createElement("tea-price");  price.amount = 4;  await import("./tea-price.js");  customElements.upgrade(price);  console.log("Off the page:", price.textContent || "nothing");  document.body.append(price);  console.log("On the page:", price.textContent);</script>
            ResultLoading…

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

              Check your understanding

              For each question, ask where JavaScript finds amount: on the element, or on its prototype.

              The early properties quiz · 7 questionsScore: first tries count
              1. Question 1 of 7A page sets price.amount = 4 before tea-price is defined. Why doesn't the class's setter run after the upgrade?

                Choose an answer to see the explanation.

              2. Question 2 of 7What does line 8 of the later-set page print?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <p>Green tea. <tea-price></tea-price></p>
                
                <script type="module">
                  const price = document.querySelector("tea-price");
                  price.amount = 4;
                  await import("./tea-price.js");
                  price.amount = 5;
                  console.log("amount:", price.amount, "text:", price.textContent || "none");
                </script>

                Choose an answer to see the explanation.

              3. Question 3 of 7In which order do the upgrade-property pattern's three steps go?

                Choose an answer to see the explanation.

              4. Question 4 of 7Your setter writes an attribute. Where should the upgrade-property pattern run?

                Choose an answer to see the explanation.

              5. Question 5 of 7What does Lit do with a property set before its element upgraded?

                Choose an answer to see the explanation.

              6. Question 6 of 7What does the class field example print?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                class TeaPrice extends HTMLElement {
                  amount = 0;
                
                  set amount(value) {
                    console.log("Setter ran with", value);
                  }
                }
                customElements.define("tea-price", TeaPrice);
                
                const price = new TeaPrice();
                price.amount = 4;
                console.log("Own property:", Object.hasOwn(price, "amount"));

                Choose an answer to see the explanation.

              7. Question 7 of 7A page writes amount="4" as an attribute on a waiting tea-price, instead of setting the property. What does the upgrade do with it?

                Choose an answer to see the explanation.

              Key takeaways

              • A property set on a waiting element becomes its own property, because the plain element has no setter for that name.
              • The upgrade keeps the same object. The own property stays, and hides your class's setter for every later set too.
              • A class field with a setter's name does the same, on every element. Store the value in a private field.
              • The upgrade-property pattern fixes it: if the element has its own property, read it, delete it, and set it again. The order matters.
              • Run it in connectedCallback() when your setter touches attributes or children, for every public property with a setter.
              • Lit does this for you. To test it, set the property before define(), then check what the element shows.

              Remember the one-liner.
              An early property hides your setter: read it, delete it, and set it again when the element connects.

              Sources

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

              Coming next: Loading definitions on demand. Load each component's code only when its tag appears on the page.

              CompleteFrontend Clear concepts. Working examples.