This has proved a difficult exercise for me. I have looked at the hints and had to go all the way to the solution, sadly, to pass the exercise. That being said, I have some questions regarding my code and the solution code.
Currently this is my code:
function updateRecords(id, prop, value) {
if(value === ''){
delete collection[id][prop];
}
else if(prop === 'tracks' && collection[id][prop] != 'tracks'){
collection[id][prop] = [];
collection[id][prop].push(value);
}
else if(collection[id][prop] === 'tracks' && prop === 'tracks'){
collection[id][prop].push(value);
}
else{
collection[id][prop] = value;
}
return collection;
}
This gets me to pass all of the requirements except for appending the tracks
array for record number 2468
So my first question is regarding the following line of my code:
else if(collection[id][prop] === 'tracks' && prop === 'tracks'){
collection[id][prop].push(value);
}
I wrote this with the intention of: if an album already had the array property tracks
then the value
would be pushed onto the end of the array. However, it does not push onto the array, it instead replaces the array with the value. So i should have 3 values in the tracks
array property however, after execution of this line there is only 1 value. Why is this?
The solution code is listed below:
function updateRecords(id, prop, value) {
if(value === "") delete collection[id][prop];
else if(prop === "tracks") {
collection[id][prop] = collection[id][prop] || [];
collection[id][prop].push(value);
} else {
collection[id][prop] = value;
}
return collection;
}
My second question is in regards to the following line of the solution code:
collection[id][prop] = collection[id][prop] || [];
What exactly is going on here? I don’t understand why the ||
is following the collection[id][prop]
after its assignment. Does this read "collection[id]prop] is assigned (itself) OR an array?
Any explanations and help understanding would be greatly appreciated!