Record Collection advice

Hello. I’m struggling a bit with JS. I managed to complete the Record Collection challenge and was wondering is there is a way to make my code cleaner or shorter? For me, this type is really straightforward and easy to understand or could I improve it? Any suggestions and advice highly appreciated :slight_smile:

function updateRecords(id, prop, value) {
   if (value === "" ){
     delete collection[id][prop]
   }
  else if (prop !== "tracks" && value !== ""){
      collection[id][prop] = value;
  }
  
  else if (prop === "tracks" && collection[id].tracks === undefined){
        collection[id][prop] = [value];
  }  else {
    collection[id][prop].push(value);
   }
  
  return collection;
}

Hey @m1rso,

as you mentioned it’s pretty straight forward and every improvement would be pretty minor, but as you asked:

  1. Technically, knowing that all arguments are strings, the only false case would be '', so you can just do if (!value).... Same goes to your collection[id].tracks === undefined check. I’ll repeat, it’s only because we expect strings only.
  2. Your second else if doesn’t need value !== "" check, because you’ve already checked it in the first if statement.
  3. Now, without that check you can combine second and third else if into one and considering the fact that you don’t need curly braces for simple one-line cases:
function updateRecords(id, prop, value) {
  const rec = collection[id];
  const trg = rec[prop];

  if (!value) delete rec[prop];
  else if (prop === "tracks") trg = trg ? [...trg, value] : [value];
  else trg = value;

  return collection;
}

Putting code aside, you should also learn that you should never ever write functions like this :slight_smile: this is very bad function! If we would live in the world of magicians, that would be black magic. FCC should really add collection to the arguments of the function, this way we at least would have grey-ish magic.

More about this: https://www.nicoespeon.com/en/2015/01/pure-functions-javascript/

Thanks for your help I do appreciate it. I have been meddling with JS for a couple of weeks so your example is a bit still too advanced for me, since I haven’t encountered " : " nor " ? " yet. Aside from that, I did check your link regarding pure and impure functions and I do understand the gist of it. I have a question regarding that. If my function is impure and it modifies the value of “collection” which is outside the scope of the function, isn’t this what we are supposed to do with this function? To modify the values of “collection”?

Yes sure, for this particular task! Just keep in mind that this is a bad pattern for your future code and try to avoid this type of functions.