Basic JavaScript: record collection question

Hi all, I have a question for future reference relating to the record collection exercise.
Is there a reason why when I tried to add the tracks property to records that didn’t have it at all using just :
collection[id][prop] = value;

It wouldn’t go through (pictured below), but when I make an empty “tracks” property and then push my value into it, it works?

Using:
collection[id][prop] = ;
collection[id][prop].push(value);

I’m a bit confused why the first method worked for other properties like artist and album, but didn’t work for the tracks. TIA for any clarification.

image

You may please provide the code in plain text, same share the challenge link too? this image is not clear. thanks.

Record Collection challenge link

function updateRecords(id, prop, value) {
  if ( value === "") {
    delete collection[id][prop];
  } else if ( prop !== "tracks") {
    collection[id][prop] = value;
  } else if ( prop === "tracks") {
    if (collection[id].hasOwnProperty(prop)){
      collection[id][prop].push(value);
    } else {
      collection[id][prop] = value;
    }
  }
  
  return collection;
}

This is becasue of

Note challeng excepted the "tracks" be kind of array, rather plain string.

So this code collection[id][prop] = value; set the prop as string, which should be an array.

tip: first initialize the collection[id][prop] as an array, then simply push the value to it

keep goin on great work, happy programming

Well take a look at these lines

    if (collection[id].hasOwnProperty(prop)) {
      collection[id][prop].push(value);
    } else {
      collection[id][prop] = value;
    }

Focus on the else block.

The task asks you this:
To create an empty array, then push the value.

What you wrote is following.
Just set it as value.

So, you are missing the step to create an empty array and putting element to that array when tracks doesn’t exist.

You can slightly change the flow and write something like this:

if ( !collection[id].hasOwnProperty(prop) ) {
    collection[id][prop] = []
}
collection[id][prop].push(value)

Thanks! That makes sense why my second method was correct then. I’ve been arguing with this problem for a while so I just couldn’t see it.

Thanks, I actually solved it with

if ( collection[id].hasOwnProperty(prop) ) {
    collection[id][prop].push(value);
} else{
collection[id][prop] = [];
collection[id][prop] = value;
}

I just didn’t understand why I needed to make the array. The answer was I needed to go back and read the prompt again :sweat_smile:

Last line
collection[id][prop] .push(value);