0

I have an if statement which evaluates

if(expression || expression &&
   expression || expression){

   //logic
} 

for a reason I cannot understand, the else statement after the and operator does not get evaluated. Is there some rules to the if statement that I do not know of?

Here is my code:

const fillTable = function (array) {
    let tbody = document.querySelector("#tblbody");
    while (tbody.firstChild) {
        tbody.removeChild(tbody.firstChild);
    }
    array.forEach(element => {
        let region = regionOption.options[regionOption.selectedIndex].value;
        let gender = genderOption.options[regionOption.selectedIndex].value;
        elementGender = Object.values(element)[2];
        elementRegion = Object.values(element)[3];
        console.log(elementRegion + "+" + region);
        console.log(elementGender + "+" + gender);

        if (elementRegion === region || region === "All" &&
            elementGender === gender || gender === "bot") {
            let tr = document.createElement("tr");
            tbody.appendChild(tr);
            const values = Object.values(element);
            values.forEach(element => {
                let td = document.createElement("td");
                td.appendChild(document.createTextNode(element));
                tr.appendChild(td);
            })
        }
    })
};

the loop continues even though the genders does not match in the if statement.

2
  • 1
    Order of operations... A good linter built into your IDE would be yelling at you for this. :) Commented Jan 11, 2019 at 21:53
  • @epascarello I am using Visual Studio Code for this. No warnings :) Commented Jan 11, 2019 at 23:24

3 Answers 3

1

You're probably getting tripped up on operator precedence. If the boolean expressions before and after the && are supposed to be grouped, explicitly group them:

if((expression || expression) &&
   (expression || expression))

Even in the absence of operator precedence rules, it's always best to be clear and explicit about the logic you're expressing.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the fast answer, I will mark you as soon as I am able to
1

It looks like the 2 lines from the if condition should each be within their own grouping operator:

if (
       (expression1 || expression2)
    && (expression3 || expression4)
) {
    // ...
} 

Comments

1

I guess you intended this

if ((elementRegion === region || region === "All") && 
     (elementGender === gender || gender === "bot"))

All the logical operators are chaining without parenthesis.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.