Everything Be True Help

Tell us what’s happening:
Can someone help tell me what is wrong with my code, and why it keeps returning false?

Your code so far


function truthCheck(collection, pre) {
  // Is everyone being true?

var falsy = [false, null, undefined, 0, NaN, '', ""];

for (var i in collection) {
  for (var j = 0; j < falsy.length; j++){
    if (collection.hasOwnProperty(pre) && collection[i][pre] == falsy[j]){
      return false;
    }
    else if(collection.hasOwnProperty(pre) == false){
      return false;
    }
    else {
      return true;
    }
    
  }
}









}

truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}, {"user": "Laa-Laa", "sex": "32"}, {"user": "Po", "sex": "female"}], "sex");

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/everything-be-true/

You need to change collection.hasOwnProperty(pre) to collection[i].hasOwnProperty(pre).
Your return true should be outside the for-loop’s blocks. Otherwise, your function returns true before iterating all the to the end of the array.

Cheers

1 Like

So would this mean I would need to get rid of the else if line too?

Dunno, that is up to your logic.

Something like this would make sense:

for (var i in collection) {
  // (FIRST IF-STATEMENT) checks if collection[i] has property pre. 
  // If it doesn't, then return false

  // (SECOND IF-STATEMENT) this will only run if the first condition is met.
  // Checks if collection[i][pre] has truthy value. Returns false otherwise.
}
// If the loop has ended and no falsy values were found, therefore there are
// none. Return true.

By the way, you don’t need the array of false value. The if-statement already uses a boolean operation. So, for example, the block following this line if (condition[i](pre)) will only run if condition[i][pre] has a truthy value.

About the Boolean, this is what I am confused about. What if there is an answer in the collection that is true/false, would it read it wrong and Booleans include all true and false values. Am I correct?