1

As we can create a object with some properties as follows:

let obj = {}; 
obj.pp1 = "abc";
obj.pp2 = 1;

Now the object will have properties pp1 and pp2.

Now I am using the same pattern inside a reduce() function to summarize the basket contents as follows:

Approach 1:

const fruitBasket = ['banana', 'cherry', 'orange', 'apple', 'cherry', 'orange', 'apple', 'banana', 'cherry', 'orange', 'fig' ];

const aggregatedBasket = fruitBasket.reduce(
  (ag , item) => {
    if (ag.hasOwnProperty(item) == false){
        ag.item. = 1;
    } else {
        ag.item += 1;
    }
    return ag;
  }, {});

  console.log(aggregatedBasket);

But when I run the code, it is returning output as:

{ item: 1 }

I know it is wrong as output is not correct, now I tried the following pattern

Approach 2:

const aggregatedBasket = fruitBasket.reduce(
  (ag , item) => {
    if (ag.hasOwnProperty(item) == false){
        ag[item] = 1;
    } else {
        ag[item] += 1;
    }
    return ag;
  }, {});
  console.log(aggregatedBasket);

Now it is printing the correct output, But I am unable to understand why . operator is failing in Approach 1.

Note: I am a beginner in JavaScript, please help me to understand. It might look simple to many experts there.

apple apple
  • 10,292
  • 2
  • 16
  • 36
Anil
  • 1,748
  • 8
  • 32
  • 67
  • 3
    Well `.` and `[ ]` are different. With `.`, the identifier on the right is taken to be the property name. With `[ ]`, the *expression* inside the brackets is evaluated, and its *result* is the property name. – Pointy Jan 18 '19 at 15:15
  • @Pointy , please explain me with an example. Thanks for the response. – Anil Jan 18 '19 at 15:15
  • Your own question is a great example! – Pointy Jan 18 '19 at 15:16
  • **With [ ], the expression inside the brackets is evaluated, and its result is the property name** - Unable to follow this line, please help me. – Anil Jan 18 '19 at 15:18
  • Try changing your working example: `ag[item + " - test"] += 1`. The code inside the `[ ]` is *evaluated* — the *result* is the property name. With `ag.item`, the property name is always just "item", and it does not matter if "item" happens to be a variable. It is *not* evaluated. – Pointy Jan 18 '19 at 15:26

1 Answers1

0

@Pointy's comment as answer

ag.item means ag['item'], not ag[item]. (unless item='item' :)

apple apple
  • 10,292
  • 2
  • 16
  • 36