Javascript Question Mark & Double Pipes - javascript

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

Related

equals comparison operator gives bad result after used four times in a row

I have a class Square with a getter method to determine if a square is valid or not. If my square has sides of 1 my code will return true. If my square has 4 sides of 5 it returns false. Can someone explain what is happening?
As you can see I accessed this in the browser and had the following results:
class Square extends Polygon {
get isValid() {
const testArray = Object.values(this);
return (testArray[0] == testArray[1] == testArray[2] == testArray[3]) ? true : false
}
The expression
testArray[0] == testArray[1] == testArray[2] == testArray[3]
carries out == 3 times, left-to-right.
((testArray[0] == testArray[1]) == testArray[2]) == testArray[3]
The first time, when the array items are equal, the first will evaluate to true:
((testArray[0] == testArray[1]) == testArray[2]) == testArray[3]
(true == testArray[2]) == testArray[3]
If the items are numbers, the next comparison will only return true if the item is 1:
console.log(true == 1);
console.log(true == 2);
console.log(true == 5);
This is because, when using abstract equality comparison ==, when a boolean is compared to a number, the boolean is coerced to a number first, and the numeric value for true is 1.
console.log(Number(true));
The third comparison has the same trouble.
To fix it, instead take the first value (or any value), and use .every:
const oneVal = testArray[0];
return testArray.every(val => val === oneVal);

Javascript short circuit if statement: How to return true

I am trying to make a function which check the value if null or ""
Here is what I got so far (that is working)
function notnull(values,success,failed){
var count = 0
$.each(values,function(index,val){
console.log(val)
val != "" && val != null ? count++ : count
})
if(count == values.length){
return true;
}else{
console.log('false')
}
}
However If I tried short circuiting the 2nd if statement it returns an error
function notnull(values,success,failed){
var count = 0
$.each(values,function(index,val){
val != "" && val != null ? count++ : count
})(count == values.length) ? return true:console.log('false')
}
the error says
Uncaught SyntaxError: Unexpected token return
Question 1: How can I return true or false in a short circuit version
Question 2: at the code
val != "" && val != null ? count++ : count
How can I omit the else part?
Your second example is a bit messy, but if I understand your function, you want to go through each value and make sure none of them are null, right?
Here is your original, cleaned up a bit:
function notNull(values){
let count = 0;
$.each(values, function (index,val) {
(val != "" && val != null) ? count++ : count
});
return count == values.length; // returns true or false
}
You are basically going through each of the values, counting them up if they aren't null, and returning true if none were null (your count is the same as your array) or false otherwise.
You are using the jQuery equivalent of the vanilla each() function. They function the same way: they'll go through every single entry in an array.
You can't short-circuit each(). Instead, you need to use some() or every(). Those functions are similar, but opposite:
some() - Continues to loop through as long as its callback returns false.
every() - Continues to loop through as long as its callback returns true.
In your case, you want to use every() because you want to go through every element and make sure it is something (in your case, not null):
function notNull(values) {
return values.every((value) => value != "" && value != null);
}
console.log(notNull([1,2,3]));
console.log(notNull([1,null,3]));
Much nicer. This will check each value. As long as they match the condition, it'll keep going and ultimately return true. If if finds one that does match, it'll short circuit there and return false.
As for your second question, how can you leave out the "else" part of this:
val != "" && val != null ? count++ : count
With the ternary operator (?:), you can't. But, you can with the normal boolean operators:
val != "" && val != null && count++;
JavaScript will short-circuit that condition at the first false, so it'll only get to count++ if the other two bits are true.
On your second example, I think you were attempting something like:
condition ? return value : console.log('a')
This would be an invalid syntax. You can only have values inside of a ternary. You could do something like this:
return condition ? value : otherValue;
If you want a return mixed in, you have to do it as two separate things:
!condition && console.log(''); // log if false;
if (condition) return value;
return and throw are both stubborn in this way and always have to be broken out and can't be mixed with other selective operators.

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

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.

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

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