Basic JavaScript: Record Collection, better solution

Basic JavaScript: Record Collection, better solution
0

#1

So I have a solution to the problem, but it seems so cumbersome. Can someone take a look and let me know how to improve my solution?

Link to the question:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/record-collection

My Solution:

if (prop !== "tracks" && value !== "")
  {

    collection[id][prop] = value;

  }

  else if (prop === "tracks" && collection[id].hasOwnProperty("tracks") === false)
    {

      collection[id].tracks = [];
      collection[id]["tracks"].push(value);

    }

  else if(prop === "tracks" && value !== "")
  {

    collection[id].tracks.push(value);

  }

  else if(value === "")
  {

    delete collection[id][prop];
    
  }
  
  
  return collection;
}

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

#3

Yeah, I saw that on the hints, but I’m not sure how the nested if else statement works. Why does if(collection[id][prop]) return a boolean?


#4

By doing this, JS will check if the value contained in collection[id][prop] is truthy or falsy.

If the value is one of the following, it will always evaluate to false, and therefore, the if will be ignored:

false
0
`''`  or  `""`  (empty string)
null
undefined
NaN

#5

Awesome, Thanks!!

So maybe the solution should be under an intermediate solution instead of beginner? Because I definitely did not know that JS had truthy or falsy expressions.


#6

What they call beginner is probably the use of procedural programming in solving problems.

That’s not the only way to solve problems if you’ve noticed and you will later learn how to do functional programming and object-oriented programming as well.

If you would like to know more about the difference between the paradigms, I suggest the following article. It could be interesting to you: Functional vs Object-Oriented vs Procedural Programming.

Congratulations on solving these algorithms.

Good Luck & Happy Coding.


#7

I’ve never heard of those terms before. I will definitely check out the article.

Thanks again!!