DEV Community

loading...

Accessing Property Names with Bracket Notation

Randy Rivera
Once I truly put my mind on something, I won't ever stop.
・1 min read
  • In the first object challenge we mentioned the use of bracket notation as a way to access property values using the evaluation of a variable. For instance, imagine that the foods object is being used in a program for a supermarket cash register. We have our function, 'checkInventory', which receives a scanned item as an argument. We've return the current value of the scannedItem key in the foods object. You can assume that only valid keys will be provided as an argument to checkInventory. We want to check our foods object for the presence of that food. This might look like:
let foods = {
  apples: 25,
  oranges: 32,
  plums: 28,
  bananas: 13,
  grapes: 35,
  strawberries: 27
};

function checkInventory(scannedItem) {
   return foods[scannedItem];
}

console.log(checkInventory("apples")); //console will display 25
Enter fullscreen mode Exit fullscreen mode

Discussion (0)