Home > database >  hey guys, can anyone explain this piece of code to me?
hey guys, can anyone explain this piece of code to me?

Time:09-30

i'm currently learning JavaScript and have to do this challenge for one of the coding challenges and the challenge is : "Create an object called 'scorers' which contains the name of the players who scored as properties and the number of goals as the value. in this game it will look like this: { Gnarby: 1, Hummels: 1, Lewandowski: 2 }" the solution : "loop over the array, and add the array elements as object properties, and then increase the count as we encounter a new occurrence of a certain element"

the object :

const game = {
 scored: ['Lewandowski', 'Gnarby', 'Lewandowski', 'Hummels']
};

the solution is :

const scorers = {};
for (const player of game.scored) {
  scorers[player] ? scorers[player]   : (scorers[player] = 1);
}

and the outcome is :

[Lewandowski: 2, Gnarby: 1, Hummels: 1]

i don't understand exactly what happens at the scorers[player] ? scorers[player] : (scorers[player] = 1); what the scorers[player] do ?

CodePudding user response:

It's a ternary operator that checks whether game contains the value of player as a property. If so, it increments the value of that property. Otherwise, it sets it to 1.

It can also be rewritten like so:

if(scorers[player]){
    scorers[player]  ;
} else {
    scorers[player] = 1;
}

If scorers does not have the value of player as a property, scorers[player] will return undefined, which, when coerced to a boolean, is false.

  • Related