Read object fields with dot and bracket syntax.

Property Access

property_access.js
const key = "pages";
const title = ({ title: "Guide", pages: 120, stock: 4 }).title;
const selected = ({ title: "Guide", pages: 120, stock: 4 })[key];

console.log("title=" + title);
console.log("key=" + key);
console.log("selected=" + selected);

Dot or Brackets

  1. The object stores title, pages, and stock.
  2. Dot syntax reads the known title property.
  3. key is pages.
  4. Bracket syntax reads the property named by key. | Access | Result | | --- | --- | | .title | Guide | | [pages] | 120 | | [stock] | 4 |
property-access Dot syntax reads a known property name. Bracket syntax uses a string expression to choose which property to read.

Exercise: property_access.js

Read one known property with dot syntax and one selected property with bracket syntax