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

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:
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.

Related

Javascript if statement needs refactoring due to bad data

Javascript if statement needs refactoring due to bad data from my database.
I want a nicer way of doing this if statement:
if (typeof value === undefined || value === null || value === "" || value === 0) {
return false;
}
Is there a shorter way?
I look forward to your suggestions.
Is there a shorter way?
Only slightly:
if (value == null || value === "" || value === 0) {
...because both undefined and null are == null (and nothing else is).
Alternately, in ES2015 you could use a Set of values you want to filter:
let badValues = new Set([undefined, null, "", 0]);
then
if (badValues.has(value)) {
If you also are happy filtering out false and NaN, then you can just use
if (!value) { // Does more values than your question asks for, see note above
Note that your first condition is wrong: If you use typeof value then undefined must be in quotes, because typeof always returns a string.
You could even do something like this:
return Boolean(value);
Note that:
!!null === false
!!"" === false
!!0 === false
!!undefined === false
You can just write:
if (!value || !value.length) {return false}
if (!value) return false;
proof - >
console.log(!undefined, !null, !"", !0);
returns -> true true true true
console.log(!100, !"hello", !"0", !"false", !"true");
returns -> false false false false false
Javascript automatically transform into boolean other variables types in if statement, you can do something like this:
if (!value || !value.length) {
return false;
}
undefined, null and 0 are transformed into "false", meanwhile with .length, if it is 0 you will still have false, otherwise another number will be true.
Cheers
EDIT
for avoiding the object {length:0} to be parsed as empty, you can add:
if (!value || ((value instanceof Array || typeof value === 'string') && !value.length)) {
return false;
}

Javascript Question Mark & Double Pipes

I am new to javascript and so far it is my understanding that:
? & : is used for "if true, do this, if false do this"
However, I am having a little more trouble with ||. From my browsing it seems something like "if the first one is true do that, otherwise do this"
I am trying to figure out the following code - any suggestions on what they mean together in this context?:
function isSubset(series, description){
var subset = true;
var exactMatch = true;
demoCodes = ['age', 'edu', 'race', 'sex'];
for (var i = 0; i < demoCodes.length; i++){
var demoCode = demoCodes[i];
subset = (subset) ? (description[demoCode] == 0 || description[demoCode] == series[demoCode]) : false;
exactMatch = (exactMatch) ? description[demoCode] == series[demoCode] : false;
}
return {subset: subset, exactMatch: exactMatch};
}
Thanks! Cheers
|| means "or". The left side of the || is evaluated first. If it resolves to true, then the expression resolves to true. If, on the other hand, the left side of the || operator resolves to false, then the right side will be evaluated and returned.
Example 1:
1 == 1 || 1 == 0
Will evaluate to true, since the left side of the || operator is true.
Example 2:
1 == 2 || 1 == 1
The left side resolves to false, so the right side is evaluated and returned. In this case, 1==1 so the whole expression (1 == 2 || 1 == 1) resolves to true.
Example 3:
1 == 2 || 1 == 3
The left side resolves to false, so the right side is evaluated and returned. In this case, 1 does not equal 3, so the whole expression (1 == 2 || 1 == 3) resolves to false.
To put it more simply, if either of the expressions "held together" by the || operator are true, then the expression will return true. Otherwise, it will return false.
subset = (subset) ? (description[demoCode] == 0 || description[demoCode] == series[demoCode]) : false;
is equal to
if(subset){
subset = (description[demoCode] == 0 || description[demoCode] == series[demoCode);
}
else { subset = false; }
The || is an or operator here and evaluates to true or false

javascript multiple OR conditions in IF statement

I think I'm missing something basic here. Why is the third IF condition true? Shouldn't the condition evaluate to false? I want to do something where the id is not 1, 2 or 3.
var id = 1;
if(id == 1) //true
if(id != 1) //false
if(id != 1 || id != 2 || id != 3) //this returns true. why?
Thank you.
With an OR (||) operation, if any one of the conditions are true, the result is true.
I think you want an AND (&&) operation here.
You want to execute code where the id is not (1 or 2 or 3), but the OR operator does not distribute over id. The only way to say what you want is to say
the id is not 1, and the id is not 2, and the id is not 3.
which translates to
if (id !== 1 && id !== 2 && id !== 3)
or alternatively for something more pythonesque:
if (!(id in [,1,2,3]))
Each of the three conditions is evaluated independently[1]:
id != 1 // false
id != 2 // true
id != 3 // true
Then it evaluates false || true || true, which is true (a || b is true if either a or b is true). I think you want
id != 1 && id != 2 && id != 3
which is only true if the ID is not 1 AND it's not 2 AND it's not 3.
[1]: This is not strictly true, look up short-circuit evaluation. In reality, only the first two clauses are evaluated because that is all that is necessary to determine the truth value of the expression.
When it checks id!=2 it returns true and stops further checking
because the OR operator will return true if any one of the conditions is true, and in your code there are two conditions that are true.
This is an example:
false && true || true // returns true
false && (true || true) // returns false
(true || true || true) // returns true
false || true // returns true
true || false // returns true

Javascript: Is there a reason to do "if (!a || (a && a.a))"?

Is there a special reason to do:
if (!options || (options && options.booleanCondition))
Instead of:
if (!options || options.booleanCondition)
I'm no javascript guru, so perhaps there's a special case or reason why the author of that code wrote it that way.
i don't see a reason to do
if (!options || (options && options.booleanCondition))
I'm no Guru but i'd stick to
if (!options || options.booleanCondition)
and save a check to the fact that options is true: in fact if options is not true the first condition is true and the second is never evaluated since it's an or condition.
That's what i think
Perhaps it's using a getter. This is a rediculous example but it can be the reason:
var o = {};
var i = 0;
o.__defineGetter__('options', function() {
return (i++) % 2 === 0 ? {booleanCondition: true} : null;
});
o.options; // Object first time
o.options; // null second time
This means:
if (!o.options || (o.options && o.options.booleanCondition))
!o.options is false (negating an object), but after that o.options is null (falsy) so then the check is mandatory.
if options.booleanCondition can change, then yes. If options is false, then the If condition will be true. If options is true, and boolean.Condition is false, then the If condition will be false. If option is true, and boolean.Condition is true, then the If condition will be true.
UPDATE
Actually, I guess it wouldn't be needed - since your simplification would be (if !true or true) if options is true, so the result would be same as (if true or true).

Any value that makes a JavaScript comparison always true?

Is there any JavaScript value that makes a comparison always true?
Example with lower than operator:
true < 10 true
false < 10 true
null < 10 true
Example with greater than operator:
true > 10 false
false > 10 false
null > 10 false
What I'm looking for:
alwaysTrue < 10 true
alwaysTrue > 10 true
I want to use this to make one part of an if statement return true by default and true or false when the first comparison value is changed.
This is probably not existent but I want to be completely sure.
You may want to consider leveraging "or" in your condition with another variable that can trump whether it returns true or not.
returnTrue || testVariable < 10
This will always return true when returnTrue is set to true, otherwise it will fall back on the comparison. If you are just looking for a change in a variable you can do so by storing the old value. If you know it will never be null you can check on this, otherwise you can use the the "or" with a flag similar to above.
oldValue === null || currentValue === oldValue
I'm not exactly sure if this is what you are asking, but this is a way of doing it with a few more statements:
var rtn = true;
if (oldCompareValue != newCompareValue) {
// next you'll want to insert your return expression
// i'm not sure you've specified what this should be
rtn = (newCompareValue > 10)? true: false;
}
return rtn;
You can also do this using the AND operator as you've requested:
rtn = true;
if ((oldCompareValue != newCompareValue) && true) {
rtn = (newCompareValue > 10)? true: false;
}
return rtn;
The if statement does the following for us:
if oldCompareValue is the same as newCompareValue then the whole statement is false
if oldCompareValue is not the same as newCompareValue then the whole statement is true
In either case the right part of the test expression always evaluates to true, and you'll only enter the if when the left part passes as well. However, keeping that true in place seems excessive to me.
Once you got you're logic in place this can go into one line.

Categories