The code below works, I had to follow the answer key to answer this problem set.
Unfortunately, I still don’t quite understand what’s happening at the first else/if statement. It’s the fourth requirement of the problem set, and I don’t understand how this code is fulfilling the requirement.
This is the problem with using someone else’s code.
Let’s back up and look at what the 4th (and 3rd) requirement is.
If prop is tracks but the album doesn’t have a tracks property, create an empty array and add value to it.
If prop is tracks and value isn’t an empty string, add value to the end of the album’s existing tracks array.
Let’s snip out the portion you are talking about for a second and look
// Only change code below this line
function updateRecords(records, id, prop, value) {
if (value === "") {
delete records[id][prop];
} else if (prop === "tracks") {
// The instructions say:
// if the album doesn't have a tracks property, create an empty array and add value to it
// otherwise, add the value to the end of the album's existing tracks array
} else {
records[id][prop] = value;
}
return records;
}
Forgetting about the solution you looked at, how could you accomplish the comments I provided? Start simple, how can you accomplish the first part, ‘if the album doesn’t have a tracks property’? If you aren’t sure, which part of the instructions are confusing you?
This is how I would write the code, but when running the tests it fails the
“After updateRecords(recordCollection, 5439, "tracks", "Take a Chance on Me") , tracks should have the string Take a Chance on Me as the last element”
part.
// Setup
const recordCollection = {
2548: {
albumTitle: 'Slippery When Wet',
artist: 'Bon Jovi',
tracks: ['Let It Rock', 'You Give Love a Bad Name']
},
2468: {
albumTitle: '1999',
artist: 'Prince',
tracks: ['1999', 'Little Red Corvette']
},
1245: {
artist: 'Robert Palmer',
tracks: []
},
5439: {
albumTitle: 'ABBA Gold'
}
};
// Only change code below this line
function updateRecords(records, id, prop, value) {
if (prop !== "tracks" && value !== "") {
records[id][prop] = value;
}
else if (prop === "tracks" && records[id].hasOwnProperty("tracks" !== true)) {
records[id][prop] = [""];
records[id][prop].push(value);
}
else if (prop === "tracks" && value !== "") {
records[id][prop].push(value);
}
else if (value === "") {
delete records[id][prop];
}
return records;
}
updateRecords(recordCollection, 5439, 'artist', 'ABBA');
The first one is explicit while the second relies upon something known as ‘short circuiting’.
So this line says “set records[id][prop] to itself if its value is truthy (an array is truthy while undefined in falsy) and set it to the empty array [] if it is not”.
Thank you so much for your help! I’ll be sure to look into short circuiting, so that I can better understand other’s code. And I’ll watch out for typos more too