The Value "male" is Returning False

I am currently on the “Everything Be True” problem in the “Intermediate Algorithm Scripting” section of the JavaScript course. I have written the code below, which works for every check except the two I have included at the end of the code (both returning false when they should return true).


function truthCheck(collection, pre) {
  let arr1 = [];
  for (let i = 0; i < collection.length; i++) {
    arr1.push(collection[i][pre]);
  }
  let truthConfirm = target => target == true;
  return arr1.every(truthConfirm);
}

console.log(truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex"));
console.log(truthCheck([{"single": "yes"}], "single"));

I entered the code I wrote into the javascript page of pythontutor.com to confirm whether my code is working as intended, and for whatever reason, while the function is indeed handling the value correctly, “male” is returning as false.

I haven’t yet checked if “female” and “yes” also return false, but because they are strings, I assume they’re supposed to return true.

Your browser information:

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

Challenge: Everything Be True

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

I just checked; both “female” and “yes” also return false according to JavaScript Tutor.

Here’s just another reason to avoid == and != at all costs.

Your truthConfirm function compares the input with true using ==. ie, you’re getting something like this:

'yes' == true

This evaluates to false. That’s not a bug, that’s JavaScript. Funnily enough,

Boolean('yes')

evaluates to true! Amazing! Whenever you need truthiness, just return the value as is (string, number, whatever) and let JavaScript do the casting itself.


Unrelated to the above, I suggest you try to solve it using a layout like this

function truthCheck(collection, pre) {
  return collection.every(item => /* your code here */ );
}

You were already on this path, but you’re making double the amount of loops necessary to create arr1 in your current code. You can just as easily access the properties of collection inside the callback function of every.

1 Like

Thank you very much for the explanation! I had a sneaking suspicion it was the ==, but for the life of me I didn’t know how to solve it :rofl:

One of the things I still struggle with is effectively writing simple code with prototype functions, so I tend to use for loops as a crutch; I want to get better at that, so thank you very much for the suggested layout as well.