Hello, I am trying to understand the following code:
// Setup
var collection = {
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(object, id, prop, value) {
if (value === '') delete object[id][prop];
else if (prop === "tracks") {
object[id][prop] = object[id][prop] || [];
object[id][prop].push(value);
} else {
object[id][prop] = value;
}
return object;
}
updateRecords(collection, 1245, 'tracks', 'Test');
The main piece of code I am trying to understand is this piece:
object[id][prop] = object[id][prop] || [];
Why are we setting the objects to be equivalent to each other when it’s already equivalent? The OR statement part I understand, or so I think.
I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.
You can also use the “preformatted text” tool in the editor (</>
) to add backticks around text.
See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).
jsdisco
November 17, 2020, 10:48pm
3
killadejavu:
The main piece of code I am trying to understand is this piece:
else if (prop === “tracks”) {
object[id][prop] = object[id][prop] || []
};
Why are we setting the objects to be equivalent to each other when it’s already equivalent? The OR statement part I understand, or so I think.
There’s two cases when prop === "tracks"
:
the corresponding object[id]
already has an array with some tracks
the corresponding object[id]
doesn’t have any tracks array yet
So what that line does:
object[id][prop]
is either equal to the object[id][prop]
array that’s already there, OR - if that array doesn’t exist, it’ll be set to an empty array.
This solution be a bit tricky. How does this solution compare to your own? What case is that line handling?