Question about logical operators

Problem code:

if ($("#indicatorType").val() === ("MFmapProvince" || "MFmapDistrict"))

Expected: Whether I switch to MFmapProvince or MFmapDistrict, I should get the same result.
Actual: When I switch to MFmapProvince, I get the expected result but when I switched to MFmapDistrict, nothing happens, i.e. the IF statement is not passing at all.

Note: I switched the order around in the IF statement to make it: ("MFmapDistrict" || "MFmapProvince") and - as I suspected - the issues reversed.

Solution code:

if (
      $("#indicatorType").val() === "MFmapProvince" ||
      $("#indicatorType").val() === "MFmapDistrict"
    )

My question is - why is the “problem code” not allowed? I checked Mozilla documentation and there doesn’t seem to be any reason it should not have worked…but perhaps I am mis-reading it?

Because that logical operator (really a selector) will evaluate first.

Here is the “thought” process. We start out with:

$("#indicatorType").val() === ("MFmapProvince" || "MFmapDistrict")

Because of order of operations (parentheses), we look at "MFmapProvince" || "MFmapDistrict" first. Remember that in JS, the logical operators don’t automatically evaluate to true or false, but evaluate to one of the values. JS sees that the first one is truthy so it evaluate to that. There is no need to even look at the second value - once the first value is truthy, we know the result of the || must be truthy. So, we end up with this:

$("#indicatorType").val() === "MFmapProvince"

The rest is clear. Moving the parentheses won’t work either - it would just create a new problem. I know that in English, “if a is equal to b or c” makes sense, but not to a computer. You have to ask “if a is equal to b or a is equal to c”.

1 Like

I was thinking about this, and there is another patter you can use if you are worried about it getting too big:

const acceptableIndicators = [
   "MFmapProvince",
    "MFmapDistrict"
 ];

const indicatorType = $("#indicatorType").val();

if (acceptableIndicators.includes(indicatorType) {
// ...

I use that patter a lot if I think the list will be big.

2 Likes