-2

This code is simple it is used to get the scanned Items and return their value if the scannedItems aren't there then it will return undefined, but for some reason the dot notation doesn't work for my function but only the bracket notation! i want to know out of curiosity why isn't it working for dot notation with detailed explanation

The code with dot notation

let foods = {
  apples: 25,
  oranges: 32,
  plums: 28,
  bananas: 13,
  grapes: 35,
  strawberries: 27
};

function checkInventory(scannedItem) {

var inventory = foods.scannedItem;

return inventory;
  
}

console.log(checkInventory("apples"));
The code with Bracket Notation
let foods = {
  apples: 25,
  oranges: 32,
  plums: 28,
  bananas: 13,
  grapes: 35,
  strawberries: 27
};

function checkInventory(scannedItem) {

var inventory = foods[scannedItem];

return inventory;
  
}

console.log(checkInventory("apples"));
albert
  • 8,285
  • 3
  • 19
  • 32
Anonymous
  • 9
  • 3
  • foods.scannedItem is checking for a key named “scannedItem”. Whereas the bracket is checking for a key based on the value the variable scannedItem points to (e.g. “apples”). – JBallin Oct 20 '21 at 18:59
  • 2
    You already know that it’s called “dot notation” and “bracket notation”. Do you know the difference between the two? What research have you done so far? All this is explained in [JavaScript property access: dot notation vs. brackets?](/q/4968406/4642212). – Sebastian Simon Oct 20 '21 at 19:01

1 Answers1

0

What comes after the dot is the name of the key which means you must know the key in advance and that is a limitation. Likely we have bracket notation that take a string letral for key name or a variable that holds your requested key for the cases when key is provided by user for example or key is passed in function args in your case.