Exercise 6 - Count Truthy not working as expected

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?

I thought the lose equality operator could be used in this way but I guess it’s only for evaluating if a string is a number or whatever.

Try running this:

const array = [1, 2, 3, 0, null, 2, 4, 5];

function countTruthy(array) {
    let count = 0;
    for (elements of array)
    	console.log(elements, !!elements, elements == true);
        if (elements == true) count++;
    return count;
}

Which yields this output:

1 true true

2 true false

3 true false

0 false false

null false false

2 true false

4 true false

5 true false

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.

3 Likes

Thanks, makes sense.