Objects and Properties
Property Access
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
- The object stores
title,pages, andstock. - Dot syntax reads the known
titleproperty. keyispages.- 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