Record collection code help

Hi there, after a few hours I tapped out to record collection. I was close but also way off. on the answer

if (value === '') delete object[id][prop];
  else if (prop === 'tracks') {
    object[id][prop] = object[id][prop] || [];
    object[id][prop].push(value);
  } else {
    object[id][prop] = value;
  }

Could someone possibly explain to me

    object[id][prop] = object[id][prop] || [];

And how this line relates to the question. All the other lines make complete sense to me but this one evades me.

Thank you

I’m not a huge fan of that line because it creates a lot of confusion.

Basically, that line checks if the tracks property is defined, and if it is not, that line initializes it with an empty array.

The || is short circuited so the first value is returned if it is defined and the second is returned if the first is not defined.

2 Likes

Great question!
I was just struggling over the same thing yesterday. Just like what @JeremyLT has said,

Basically, that line checks if the tracks property is defined, and if it is not, that line initializes it with an empty array.

And to go deeper, you can see that there are two scenarios under the else if (prop === 'tracks') condition,

  1. The value’s not empty and the record has the “tracks” property
  2. The value’s not empty and the record doesn’t have the “tracks” property so the line of code in question is actually trying do deal with both scenarios at once.

And apparently in JS, the OR operator can have non-boolean operands and these expressions below can be converted to false:

  • null ;
  • NaN ;
  • 0 ;
  • empty string ( "" or '' or ```` );
  • undefined .

So here’s how you can think about that line of code:
(left side) the object[id][prop] object, which is the track’s array
(is equal to)
(right side) the track’s array itself, if it exists (not null), and the line finishes since you already have a True value, BUT if the array doesn’t exist, the expression evaluates to null, and is interpreted as a False, and thus it continues with the || [ ] (or an empty array), and the boolean expression evaluates to the “True value” the empty array, since it’s not null.

(Here’s the official documentation on how the OR operator in JS works)

1 Like