Search code examples
javascriptarraysfor-of-loop

Why does this code runs correctly with loose equality than with strict equality?


I tried to code the snippets with both strict equality and loose equality to count the total number of truthy values in the given array.

The code runs correctly with the loose equality

let array = [0, '0', true, 100, false, NaN];

countTruthy(array);

function countTruthy(array){
    let count = 0 ;
    
    for (let element of array){
        if (element == (null || undefined || NaN || false || 0 || '')){ //comparing with loose equality
            continue;
        }
        console.log(element);
        count++
    }
    console.log (`The total truthy in the array is : ${count}`);
}

While the code gives incorrect count with strict equality.

let array = [0, '0', true, 100, false, NaN];

countTruthy(array);

function countTruthy(array){
    let count = 0 ;
    
    for (let element of array){
        if (element === (null || undefined || NaN || false || 0 || '')){//Using the strict equality
            continue;
        }
        console.log(element);
        count++
    }
    console.log (`The total truthy in the array is : ${count}`);
}

I also tried the

console.log(undefined === undefined);

Why am I getting the wrong count with strict equality while correct count with loose equality?

I also know there is efficient way to write the same code. So please give suggestions only for the above issues I am facing.


Solution

  • When you use a chain of ||s, the whole expression will evaluate to the first truthy value, if there is one - otherwise, it will evaluate to the final (falsey) value. So

    (null || undefined || NaN || false || 0 || '')
    

    is equivalent to

    ('')
    

    With strict equality, none of the array items are the empty string, so all pass the test.

    With loose equality, only 0 and false are == to the empty string.

    console.log(
      0 == '',
      false == ''
    );

    With Abstract Equality Comparison:

    For 0 == '': When a number is compared against a string on the right, the string gets converted to a number, and 0 == 0 is true

    1. If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).

    For false == '': When a boolean is compared against a string on the right, the boolean is converted into a number first:

    1. If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.

    Then the string is converted into a number:

    1. If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).

    and 0 == 0 is true.