JavaScript, inside out · Chapter 30 of 51

Getters, setters and static

By the end of this chapter you can make properties that run code when they are read or written, build objects with static factories, and set a property's flags with Object.defineProperty. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: The kitchen
  • 5 tasks
  • JavaScript
  • In the all labs plan

The first 2 chapters of JavaScript, inside out are free. This one comes with the all labs plan.

Why you need this

Ravi has two complaints. An order showed ₹80 after a bun maska was added to it, because its total was worked out once and stored. And a delivery went astray because a phone number with eleven digits was saved without a check. Meera also wants the menu's price locked and its cost hidden from the public JSON, and Kabir wants orders built straight from kitchen printer tickets.

With what you know so far, a total is either a stored value that goes stale or a method that every caller must remember to call with brackets. Any code can write any value into a property, and every property shows up in Object.keys and JSON.

What you build: 5 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    Order: a total worked out on every read

    Give Order a getter, total, that adds up price times qty over the order's items every time it is read, and remove the stored total from the constructor. An order's only own key is items.

    new Order([{ name: 'masala chai', price: 40, qty: 2 }]).total gives 80; after a bun maska at 35 is pushed onto items it gives 115, and a changed qty counts too. An order with no items gives 0.

    total has no setter: assigning to it throws a TypeError.

  2. Task 2

    Customer: a phone setter that cleans and checks

    Give Customer a private field #phone, a getter phone that returns it, and a setter phone. The setter removes every space and dash; what is left must be exactly 10 digits, otherwise it throws a RangeError and the old number stays. The constructor sets name and then sets phone through the setter, so a bad number throws there too.

    new Customer('Anjali', '98450 12345').phone gives '9845012345', and '99001-23456' is saved as '9900123456'. '98450 123456' (11 digits), '98450 1234' (9) and '98450abcde' are all rejected. A customer's only own key is name.

  3. Task 3

    ChaiOrder.fromTicket: a static factory with a count

    Add a static method fromTicket(text) to ChaiOrder. A ticket is the item, a space, x and the quantity, a space, @ and the price: ChaiOrder.fromTicket('masala chai x2 @40') returns a ChaiOrder with exactly the own properties item 'masala chai', price 40 and qty 2 (numbers, not text). Anything else gives null: 'chai please' and 'bun maska x @35' (no quantity) both give null.

    ChaiOrder.created is a static getter that says how many ChaiOrders have been made so far, by fromTicket or by new. Keep the count in a private static field: Object.keys(ChaiOrder) must stay empty, and assigning ChaiOrder.created = 0 must not change it. An order itself has no fromTicket.

  4. Task 4

    prepareMenuItem: lock the price, hide the cost

    Write prepareMenuItem(item, cost). Change the item in place and return the same object. price keeps its value and still shows in Object.keys and JSON, but becomes read-only and cannot be deleted or redefined (writable and configurable false, enumerable true). Add cost as a hidden property: item.cost gives the cost, but it is not in Object.keys or JSON.stringify, and it is read-only.

    prepareMenuItem({ name: 'masala chai', price: 40 }, 18) gives an item whose keys are name and price and whose cost is 18. Assigning price or cost, or deleting price, then throws a TypeError. name is left alone and can still change.

  5. Task 5 · interview question

    Interview: watch, report every change to a property

    Write watch(obj, key, onChange). Replace obj's key with a getter and setter made with Object.defineProperty, change obj in place and return the same object.

    Reading the key still gives the current value. Every assignment that changes the value calls onChange(newValue, oldValue), new value first. Assigning the value it already has does not call onChange. The key stays enumerable, so Object.keys and JSON.stringify still show it, and two watched objects never share a value.

What you will learn

  • Getters: a property worked out each time it is read.
  • Setters: code that checks a value before it is stored.
  • Static factories and private static fields: build objects from other data, and count them where nobody can reset the count.
  • Object.defineProperty: choose whether a property can be changed, deleted or seen.

More in The kitchen

Build "Getters, setters and static" yourself

Tapri, a chai brand going online, needs its menu, orders and kitchen in code. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

The first 2 chapters of JavaScript, inside out are free. This one comes with the all labs plan.