Record Collection - Curious about something

Hi, so I’ve been messing with Record Collection Challenge and I have a question.

I’ve managed to figure out how everything works except for one part.

It says - If prop is "tracks" but the album doesn’t have a "tracks" property, create an empty array before adding the new value to the album’s corresponding property.

Now I know that this piece of code works if I use:

collection[id][prop] = [value];

But I can’t figure out why it doesnt work if I use.

collection[id][prop] = [];
collection[id][prop] = value;

Here’s my code.

  if(prop !== 'tracks' && value !== ''){
    collection[id][prop] = value;
  }
  
  if(prop === 'tracks' && value !== ''){
    if(collection[id][prop]){
      collection[id][prop].push(value);
    }
    else{
      collection[id][prop] = [value];
    }
  }


  if(value === ''){
    delete collection[id][prop];
  }

  return collection;
}

The first of the above lines assigns an empty array to collection[id][prop]. The second value to collection[id][prop]. Basically, it is as if the first line never executed. You replaced the array with value.

2 Likes