← Back to the exercise

Working with Objects

The answer to the exercise in Working with Objects.

Two changes, one per bug:

  • show.key looked for a property literally named key. Brackets take the expression, so show[key] reads the property the caller asked for.
  • || falls back on every falsy value, which swallowed the 0 and the empty string. ?? falls back only on null and undefined, so the fallback now appears solely when the property is absent.
const show = { title: "Severance", rating: 0, network: "" };

function read(key) {
  return show[key] ?? "not set"; // was: show.key || "not set"
}

console.log("title:  ", read("title"));
console.log("rating: ", read("rating"));
console.log("network:", read("network"));
console.log("missing:", read("missing"));