Record Collection explanation

Record Collection explanation
0

#1

Greetings distinguished fellow campers! I’ve been having some troubles understanding the solution of this task and hope you will be able to help me.

The solution goes like this:

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;
}

What does the condition in the third line mean?


#2

Remember “Falsy Bouncer”, where we learned about how values are either “truthy” or “falsy”? This condition is using that. The condition will be met for any truthy value. If it is falsy (undefined, null, an empty string, etc) then the else will execute.


#3

Right! So while [id] and [prop] have valid data behind them (correct format an not zero) this statement will be executed. Thank you for help!

By the way, how can we reverse that? This expression checks if the input is true, but how can we do the exact same for "false input?


#4

You can use the negation operator:

if(!thingThatMightBeFalsy) {
    console.log('the thing was falsy');
}

#5

So, in our example it will look like this:
if (!collection[id][prop])
meaning
if (the input is false)
?


#6

I’m not sure what you mean by “the inpt is false”. !collection[id][prop] would mean that looking up collection[id][prop] resolved to a falsy value. That could mean that collection[id] doesn’t have a property with the name contained in prop (undefined) or that it contains a falsy value (0, '', null, false, ‘NaN’).


#7

You’re right, thank you!