I have found a solution for one of quiz I have in working with JavaScript data structure, in which an object (named game) was given as following.
const game = {
score: '4:0',
scored: ['Lewandowski', 'Gnarby', 'Lewandowski', 'Hummels'], //Names of players
date: 'Nov 9th, 2037',
odds: {
team1: 1.33,
x: 3.25,
team2: 6.5,
},
};
Quiz or challenge is: Create an object called 'scorers' which contains the names 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
}
I found the following solution:
let scorers = {};
let arr = Object.values(game.scored);
for(const player of arr) {
scorers[player] = (scorers[player] || 0) + 1;
}
console.log(scorers);
// {Lewandowski: 2, Gnarby: 1, Hummels: 1}
My question is how the syntax scorers[player] = (scorers[player] || 0) + 1; produces values for each player property though it will be true or false, and how at the end 1 will be added though it is of type number? How to interpret this code in simple language?
Unlike some other languages, JavaScript allows other data types to be used for what looks like purely boolean operators. In that case JavaScript will temporarily interpret a non-boolean as being "falsy" or "truthy".
There are two cases:
scorers[player] is undefined. In that case the || operand will identify that value as a "falsy" value and will thus continue to evaluate the right operand, which is 0. So (undefined || 0) evaluates to 0.
scorers[player] is defined, and (for this program) it will be a positive number. In that case the || operand will consider it "truthy" and not evaluate the right operand. So (1 || 0) evaluates to 1.
NB: In modern JavaScript it is now better practice to use the ?? operator for this use case instead of ||.
The syntax scorers[player] || 0 is called short circuit in JavaScript.
It is as simple as AND, OR AND NOT in Logical algebra. By default, a non-existing property in JS Object yields undefined( which means Boolean false ).
Here are some uses of the short circuit in JS.
Your statement scorers[player] = (scorers[player] || 0 will result the socres[player] result if it exists or 0. When you did add 1 to it at, it will increment the current player goal count. That will result in 0 or +1 to the current score of the player. Each step involved in that statement is shown below.