Record Collection (problem understanding code)

Hi I was struggling so I looked at the solution (given below):

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

  return collection;
}

I don’t understand what the code in bold does. Also, why is and else if coming after else? TIA.

It’s a nested if-statement, so the first else-statement is in response to the second if-statement, if that makes sense.

function updateRecords(id, prop, value) {
  if (prop === "tracks" && value !== "") {
  //Now we're in the first if-statement, and here we check if the
//prop is equal to "tracks" and the value is not an empty string

   if(collection[id][prop]) {
   //We write another if-statement within the first one, where we check if
   //our JSON-object has this particular prop (tracks, from the first if-statement).
   //Note, the reason why this is possible is because if we try to access an index
   //which is invalid, it returns undefined, which in turns gives a false in an if-statement

   //If it turns out that we do have a tracks-prop, we push the value there, since tracks is an array
    collection[id][prop].push(value);
   }

   //Otherwise, we give the collection a tracks prop, and make it an array containing the value
   else {
    collection[id][prop]=[value];
   }

  //This last else if is in regards to the first if-statement, as in,
  //we either don't have a tracks prop, the value is empty, or both.
  //We then narrow down this statement with a check for if the value is NOT empty
  } else if (value !== "") {
    //If it is, we assign the tracks prop in our collection to the value.
    collection[id][prop] = value;

  //Otherwise, we delete this prop
  } else {
    delete collection[id][prop];
  }

  return collection;
}

Sorry if this is super messy or if I misunderstood in any way, but I hope it makes sense!

1 Like

There are three main if statements here:

1. if (prop === "tracks" && value !== "")
2. else if (value !== "")
3. else {}

No. 1 then has additional statements in there:
1a if (collection[id][prop])
1b else {}

It is always useful to count the brackets to see what ends where.

2 Likes

I just noticed this last night xD Thank you so much

1 Like

I’ll keep the bracket thing in mind. Thank you!