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
};
I would not call this concatenation. The double ampersand represents the logical AND operator. In general you can have as many operands as possible:
Each
operand
should be, or at least should be evaluated to a boolean value -true
orfalse
. The logical result is applied on the evaluated boolean values as follows:Logical AND (
&&
)This means that if any operand is evaluated to
false
, the whole evaluation is resulting asfalse
(true && true && false
becomesfalse
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 (
||
)Effectively
false || false || false || true
evaluates totrue
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 totrue
-
(true && false) && (false || true)
evaluates tofalse
In your particular code snippet:
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 theif
statement does not get executed.