I will answer myself with some of the steps I’ve done to understand my doubts.
Starting with updateRecords( ) as a function that takes as parameters (records, id, prop, value)
where arguments are:
- records = Object Literal
- id = nested object (number)
- prop = nested object property name (i.e. “artist”)
- value = value of the property of the nested object (i.e. “Robert Palmer”)
This can be seen when the function is declared at first:
function updateRecords(records, id, prop, value) {
//function code here
};
And the arguments are given at the end of the code. (And fCC tests other arguments out of the code itself)
updateRecords(recordCollection, 5439, 'artist', 'ABBA');
So, when the function needs to access the albums of recordsCollection
it will always be records[id]
because this points to the nested objects which are named by numbers. Otherwise will search for the parameters in the object literal and wouldn’t be able to find them (because they’re not), will only find numbers.
This is what I needed to do for understand all the lines in the code:
function updateRecords(records, id, prop, value) {
if (prop !== "tracks" && value !== "") {
// If prop argument is strictly different from "tracks" AND value is strictly NOT an empty string
records[id][prop] = value;
// invoke Object literal(recordsCollection) with the specific nested object (id) and the property of it; assigns value to the value of that property
}else if (prop === "tracks" && !records[id].hasOwnProperty(prop) ) {
//If the given argument of prop is strictly "tracks" and recordCollection with it's nested object returns false when checking for tracks
// !records.hasOwnProperty(prop) IS ALSO records.hasOwnProperty(prop) === false
// When searching with .hasOwnProperty() this can be either ("tracks") or (prop) because you're earlier conditioning that prop has to be strictly "tracks"
records[id][prop] = [value];
//invoke Object literal(recordsCollection) with the specific nested object (id) and the property of it; then assign an array with a value using the value parameter
}else if (prop === "tracks" && value !== ""){
//If the given argument of prop is strictly "tracks" and the value has something (is not empty)
records[id][prop].push(value);
//invoke Object literal(recordsCollection) with the specific nested object (id) and the property of it and uses .push() method to add the value at the end
}else if (value === ""){
// If the value of value argument is strictly empty
delete records[id][prop];
// deletes in the Object Literal (recordsCollection) with the specific nested object the property
}
return records;
}
If I’m being wrong or something does not make sense, please let me know. I just tried to figure out every single thing that the code does to understand it better, and try to explain with my best words.