For the Basic Javascript topic “Record Collection” I am having trouble understanding the difference in behavior with different syntaxes.
My solution (which is valid) is as follows:
function updateRecords(records, id, prop, value) {
if (value == "") {
delete records[id][prop];
}
else if (prop != "tracks" && value != "") {
records[id][prop] = value;
}
else if (prop == "tracks" && (records[id].hasOwnProperty("Tracks") == false || value != "")) {
records[id][prop] = records[id][prop] || [];
records[id][prop].push(value);
}
return records;
}
(Note: the last else if statement could be changed to an open else statement, but that is less specific/less qualified)
I have tried changing this around a bit just to see what will work and what won’t so that I understand how accessing and changing object property values works, but this has just made me more confused.
If I change records[id][prop] = value; to records[id][prop] = [value] or records[id][prop].push(value); this evaluation no longer works, but I can’t see why - it seems exactly the same to me.
Likewise if I change the push statement in the second else if statement to update the value of the records[id][prop] value, that doesn’t work. WHY?
Lastly, considering these work the same in my head I tried to push both else if statements together to just evaluate as an else statement that initializes the prop value of the records array if it doesn’t exist, then either push the value or set the value. Neither of these works and again, the fact that these appear to work differently is why it doesn’t work but I still don’t understand the rules for what exactly is going on to understand why this is the case.
Any help with what exactly the difference of pushing a value vs. assigning a value and the difference of assigning value vs. [value] would be much appreciated.
Thanks,
Kyle