Record Collection - Basic JavaScript (Legacy JavaScript Algorithms and Data Structures)

Hi,

I think I have a problem with the statements in my if function.

Below is my code. However when I run the challenge it doesnt work. I have no idea why. Below that is the answer. The difference seems to be that the third condition is nested into the else if statement. As opposed to my condition where I just shoved it all together.

I suspect the problem is I tried to make the if statement do 2 things at once. Perhaps that is the problem ? My intentions are; if all three conditions are met, an empty array should be created and ‘value’ should be pushed onto it.

Please help. Much thanks.

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

What do you mean it doesn’t work?

else if(prop=='tracks' && value!='' && records[id].hasOwnProperty('tracks')==false){
    records[id][prop]=[];
    records[id][prop].push(value);
  };
else if (prop === "tracks" && value !== "") {
    if (records[id].hasOwnProperty("tracks") === false) {
      records[id][prop] = [];
    }
    records[id][prop].push(value);
  }

The difference between the two is:

  • Top one will push value to the array only if there isn’t tracks property previously. If there is tracks property already, code will be skipped.
  • In the bottom one, value will be always pushed to array. If there isn’t already tracks property, it will be added before that.

I’ve just realized I missed the last condition in the challenge. It explains why the if statement is nested. I’ve kinda solved it now. Thanks for pointing this out to me.