So my interpretation of the exercise was almost perfect except it didn’t work (kept giving a value of 0 or 1 depending what the first element in the array was.)
So I watched for Mosh’s answer to find it was almost identical except I was evaluating- if (true) -with too much complexity.
So here’s my attempt:
const array = [1, 2, 3, 0, null, 2, 4, 5];
console.log(countTruthy(array));
function countTruthy(array) {
let count = 0;
for (elements of array)
if (elements == true) count++;
return count;
}
and here’s the code block that DOES work:
const array = [1, 2, 3, 0, null, 2, 4, 5];
console.log(countTruthy(array));
function countTruthy(array) {
let count = 0;
for (elements of array)
if (elements) count++;
return count;
}
So my question is: Why does if (variable == true) statement not work? what’s going on here?
So we can see that only 0 and null are falsey but the loose equality operator only returns true for 1 - this is because it loosely equates 0 to false and 1 to true, in true binary boolean style.