Logic not clear

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"
    }
};
// Keep a copy of the collection for tests
var collectionCopy = JSON.parse(JSON.stringify(collection));

// Only change code below this line
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;
}

The above is the complete code. Can anyone explain me the logic for the below code?

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’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.

markdown_Forums

Also, we prefer that you not post working solutions in general to the forum.

Instead of us trying to explain the above solution to you, why don’t you tell us which parts you are having trouble understanding? Did you try coming up with your own solution before looking at this one?

Thanks a lot for educating me. This is the first time i posted here, so in urgency i didn’t notice how the code looks for others. Sorry for that.

Also my doubt is, if we print the value of

collection[id][prop]
The output is:
undefined

So in the if-condition, how is the undefined value evaluated to be true or false. When will the condition be true in the undefined case.

collection[id][prop] isn’t always undefined in this function, but sometimes it will be. And when it is, it evaluates to false because it’s a falsy value.

Further info: https://developer.mozilla.org/en-US/docs/Glossary/Falsy

Try doing a console.log(collection[id][prop]) just inside the first if statement and see what the values are when you change the function parameters.