// Setup
var collection = {
2548: {
album: "Slippery When Wet",
artist: "Bon Jovi",
tracks: [
"Let It Rock",
"You Give Love a Bad Name"
]
},
2468: {
album: "1999",
artist: "Prince",
tracks: [
"1999",
"Little Red Corvette"
]
},
1245: {
artist: "Robert Palmer",
tracks: [ ]
},
5439: {
album: "ABBA Gold"
}
};
// Only change code below this line
function updateRecords(id, prop, value) {
if(prop!="tracks" && value !==""){
collection[id][prop] = value;
}
else if(prop == "tracks" && collection[id].hasOwnProperty["tracks"] == false)
{collection[id][prop] = [];}
else if(prop == "tracks" && value !=="")
{collection[id].tracks.push(value); }
else if (value ===""){
delete collection[id][prop];
}
return collection;
}
updateRecords(5439, "artist", "ABBA");
After updateRecords(5439, “tracks”, “Take a Chance on Me”)
, tracks should have “Take a Chance on Me” as the last element.
I have checked all solutions for this and everywhere i see that the line concerning this error is the same as mine but their code work.
let’s try to run this function call that is giving you issues:
so I delete the function call that is present in the editor, and substitute it with the function we want to test:
...
return collection;
}
-updateRecords(5439, "artist", "ABBA");
+console.log(updateRecords(5439, "tracks", "Take a Chance on Me"))
now we should see what the result is, but, oh, there is an error! It says
TypeError: collection[id].tracks is undefined
so it means that the function stops running somewhere.
I am going to use JavaScript Tutor to check where it stops
it stops at the line
{collection[id].tracks.push(value); }
it means that there is something wrong in this line or above it.
If we look carefully we can see that here we have a syntax error: collection[id].hasOwnProperty["tracks"]
, as hasOwnProperty
is a method, it requires round parenthesis to be used. So let’s change that to collection[id].hasOwnProperty("tracks")
and try again
Well, now the output is again wrong, if we look at the object 5439
there is anb empty array: '5439': { album: 'ABBA Gold', tracks: [] }
and why there is an empty array?
well, because we have
else if(prop == "tracks" && collection[id].hasOwnProperty("tracks") == false)
{collection[id][prop] = [];}
else if(prop == "tracks" && value !=="")
{collection[id].tracks.push(value); }
and in a chain of if-elseif-else staments only one of them will execute.
how to solve this? there are some ways, but all needs for the checking if the tracks property exist happens in a way that the push
method will be executed anyway.
This can be done with nested if statements, a ternary operator, shortcircuit evaluation… up to you to try and make it work