Challenge Guide: Record Collection deep explanation

Сan someone provide a deeper explanation of this line in solution:

collection[id][prop] = collection[id][prop] || [];
2 Likes

It reads the same way it’s written:

collection[id][prop] equals to itself or empty array (in case itself is undefined)

So if tracks property has an array of tracks (not undefined) you will re-assign it to itself, practically changing nothing, and if collection[id] doesn’t have property tracks (undefined) you will assign empty array to it

1 Like

if the argument prop === “tracks”:
case 1: {---- there is a “tracks” property in the collection object ----}
so let’s start with setting the value of the object[id][prop]
according to the || operator there is two operands(choices) object[id][prop] || []
let’s try on the first choice object[id][prop]:
1- || operator will check its value either true or false
**note it will be false if equals one of falsy values 0, null, undefined, false, NaN, "", ''
2- according to the upper values it is true
3- according to the “logical operators short-circuiting behaviour” this value will be taken as the value of the object[id][prop] and other operand will not be considered([] is skipped)
4- now we have object[id][prop] set to tracks: [‘found’]
5- last step is clear is to push(value) method
----------------------------
case 2: {---- there is NO "tracks" property in the collection object ----}
…SAME AS ABOVE STEPS TILL STEP 2
2- according to the falsy values object[id][prop] is false(literally: undefined)
3- the || operator has to check the second operand this time (no short-circuiting here) which is an empty array so it will be true (not one of the falsy values) and will be taken as the value of object[id][prop]
4- now we have [] set to object[id][prop] leading to creating a new array
and so on… just as above

I hope this can help.

5 Likes

thanks so much for this explanation!