Is it possible to concatenate 3 queries with the && operator?

1.2k views Asked by At

I have some JavaScript on my page that checks the indexOf to find one of a multitude of strings in my URL, it then performs a function that scrolls to a set position on the page.

I currently am using the following code to concatenate 2 conditions, but I need to incorporate a 3rd condition. When I add an additional line and an additional && my JavaScript fails. Can anyone recommend a better solution?

My current working code:

    if (window.location.href.indexOf("search_categories") > -1 && 
        window.location.href.indexOf("search_region") > -1) {
        // do some stuff 
    };

The failing code:

if (window.location.href.indexOf("search_categories") > -1 && 
    window.location.href.indexOf("search_region") > -1 && 
    window.location.href.indexOf("upload-a-cv") > -1) {
    // do some stuff 
};
1

There are 1 answers

0
Ivaylo Slavov On BEST ANSWER

I would not call this concatenation. The double ampersand represents the logical AND operator. In general you can have as many operands as possible:

operand1 && operand2 && operand3 ...

Each operand should be, or at least should be evaluated to a boolean value - true or false. The logical result is applied on the evaluated boolean values as follows:

Logical AND ( && )

true && true = true
true && false = false
false && true = false
false && false = false

This means that if any operand is evaluated to false, the whole evaluation is resulting as false (true && true && false becomes false in the end).

In case you want to allow any condition (operand) to cause the result to be true, you would have to use the

Logical OR ( || )

true || true = true
true || false = true
false || true = true
false || false = false

Effectively false || false || false || true evaluates to true

If you want to have certain groups of conditions to be all true, and the another group where at least one is true, you have to group them, using braces as in:

-(true && false) || (false || true) evaluates to true
-(true && false) && (false || true) evaluates to false


In your particular code snippet:

if (window.location.href.indexOf("search_categories") > -1 && 
window.location.href.indexOf("search_region") > -1 && 
window.location.href.indexOf("upload-a-cv") > -1 ) ...

it is enough to lack at lease one of the parameters in the request, to have the if expression evaluate to false, therefore the body of the if statement does not get executed.