Record Collection alternative solution

Tell us what’s happening:

Hey! I came up with a solution to the Record Collection challenge that seems to differ quite a bit from the official solution and was wondering if someone with more experience could tell me if there were any disadvantages to my version? It seems to pass all the tests.

Code:


function updateRecords(id, prop, value) {
  
  var entry = collection[id];

  if (value !== "") {
    if (prop === "tracks") {
      if (entry.hasOwnProperty("tracks") === false) {
        entry.tracks = [];
      }
      entry.tracks.push(value);
    } else {
      entry[prop] = value;
    }
  } else {
    delete entry[prop];
  }

  return collection;
}

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/record-collection

The only thing that stands out to me is if (entry.hasOwnProperty("tracks") === false). You never need to compare the contents of an if condition to true or false because that condition is always evaluated as a boolean.

// you have
if (entry.hasOwnProperty("tracks") === false) {
        entry.tracks = [];
      }
      entry.tracks.push(value);

// which would be better as
if (!entry.hasOwnProperty("tracks") ) { // use the "not" operator
        entry.tracks = [];
      }
      entry.tracks.push(value);

There are a few things that you would normally want to do but which aren’t tested in this challenge, like handle the cases where collection[id] or entry[prop] don’t exist.

1 Like

Ah yeah, it looks like I’ve missed a bunch of cases that are handled by that solution. Didn’t notice those until you pointed them out. I’ll try to rewrite mine to incorporate those checks. The “not” operator is also a lot more concise, I’ll fix that. Thanks a lot for your time, this was really helpful!

Sorry, I’m new to these forums and wasn’t aware of that. I’ll keep that in mind for next time. :slightly_smiling_face: