Hi guys, can’t figure out what’s wrong with my code. Some of the trues are coming up false and I have no idea why. Please help if you can. Many many thanks in advance
/* Check if the predicate (second argument) is truthy on all elements of a collection (first argument).
Remember, you can access object properties through either dot notation or [] notation.
*/
function truthCheck(collection, pre) {
var hold = "";
// Is everyone being true?
for (var i=0; i<collection.length; i++) {
console.log(collection[i], pre, collection[i][pre]);
if(collection[i][pre] === undefined || collection[i][pre] === 0 || collection[i][pre] === "" || collection[i][pre] === null || isNaN(collection[i][pre]) === true) {
hold = false;
break;
} else
hold = true;
}
return hold;
}
truthCheck([{"single": "yes"}], "single"); // this is returning false? :(
uh huh, that would actually makes a lot of sense cause when I was trying my code on python tutor and console logging the result of the if statement it will only console log once and stop.
Can’t wait to be like you guys when i grow up lol…it’s amazing to see how some of you come up with the simplest methods when it takes me hours to not even have it figured out, I’ve only been at this for a little over 2 months, but i’m looking forward to being able to form solutions as easy as you all.
It’s simple. In your code when if condition is true (collection[i][pre] == true), function returns true. So if first object will satisfy the condition, for loop will be stopped and won’t check other objects in collection. That’s why we have to detect false, not true.