Order of statement evaluation [duplicate] - javascript

This question already has answers here:
Does JavaScript have "Short-circuit" evaluation?
(3 answers)
Closed 5 years ago.
I have this code
if (!caught.includes("AreYouHuman") && !caught.includes("pfail=1") && caught.includes("Episode") && caught.includes("Anime")) {
var arraystring = caught.split("&s");
var updating = chrome.tabs.update({url: arraystring[0] + "&s=beta&pfail=1"});
}
"caught" is a URL which I get from the browser.
1)would JavaScript stop at the first false statement it counters ( assuming that it iterates over them linearly ( AreYouHuman --> pfail=1 --> Episode -->Anime)).
2)or does it evaluate all of the statements at once then decide whether the whole thing is true or false ?
Assuming that 1) is the correct option, placing the least likely condition to be true,on the first position, would theoretically increase my code execution speed right ?
About the "duplicate" flag non-veteran programmers (like me) won't know "Short-circuit” and probably are not looking for the difference between "&" and "&&", there search would be how does javascript evaluate booleans in an "if statement"

Because you are using the short-circuit logical AND operator &&, yes, the entire expression will return false when the first of the expressions fails.
If, however, you were using a single &, then it would be a bitwise operator not be short-circuited and would continue to test the remaining conditions even if one were to return false.
The conditions are tested according to order of operations, but barring any grouping operators, the expression is evaluated left to right.

Yes, javascript interpreter stops at first false statement, from left to right. If a false value is encountered, it stops the tests, as the expression will evaluates to FALSE whatever the other values are

Related

Why "if(!!variable)" instead of "if(variable)"? [duplicate]

This question already has answers here:
What is the difference between if(!!condition) and if(condition)
(3 answers)
When to use the double not (!!) operator in JavaScript
(2 answers)
Why use if (!!err)?
(3 answers)
Closed 6 years ago.
In someone else's code I found this way to test the existence of a variable :
if(!!variable) {
//Do something
} else {
//Something else
}
Is there a reason to test with if(!!variable) instead of if(variable) ? Is it a good practice?
Is there a reason to test with if(!!variable) instead of if(variable)?
No.
Using if() will coerce the condition to a boolean anyway, there's no need to manually do it. Using this sort of syntax makes sense when you want to guarantee you've got a boolean elsewhere, for example if you wanted to log the truthiness of the expression:
console.log(!!variable)
This will ensure that you get either true or false logged, rather than the original value of the variable. But inside an if? It makes no difference.
No, in the case of a if, their is usually no reason to write that in JS.
I would not call it bad practice, since it can often come from programmer coming from strongly typed language, and is a common quick way to do the conversion to bool in thoses language.
It can also be used to emphasise the importance of the truthiness of the value in a long if, and show the programmer didn t forget to put the condition.
TL:DR: As for a lot of things: it may not be good practice, but it only become bad practice if your team is not used to that practice, either train them, document, or leave it.
Double negation is a bit of a hacky way (IMHO) to convert a variable to bool. using ! on variable coerces it to a bool and negates it, and using it again convert it back to the 'correct' value. So !!0 === false
As mentioned by James there is no reason to do this inside an if statement. The only reason really to do this would be to coerce to a bool for logging purposes or similar so the value logged is true or false rather than 0, an empty string etc
Double ! (!!) is not an operator. It's just ! twice - double negation.

Double-negation + logical and in Javascript [duplicate]

This question already has answers here:
Why don't logical operators (&& and ||) always return a boolean result?
(9 answers)
Closed 7 years ago.
I just ran across this code
var someBool = !!(o.a && o.a.t);
I was about to remove the double-negation, then realized it forces someBool to be a boolean value... Looking on the MDN, I find this example
a5 = "Cat" && "Dog"; // t && t returns "Dog"
This seems atypical based on my experience in other languages. I'd expect the logical and operation to always return a boolean value. Can anyone explain why this use case is supported in Javascript?
Also, is the code that sent me in this direction the best way to force a bool around logical and? I'm aware of new Boolean, but that doesn't return a primitive type like the double-negation, so perhaps that's the way to go?
The && and || operators have an effect similar to boolean AND and OR, but they don't affect the expression value. The expressions are evaluated and the values tested with the JavaScript "truthiness" rules, but the overall expression value is that of the actual operand expressions (well, one of them).
Yes, that's different from C and Java and etc. JavaScript is a different language with its own rules.
The Boolean constructor can be called without new to perform a "truthiness" test and return a boolean primitive. Using !! is fairly idiomatic however.

In JavaScript, does an if with multiple or's evaluate all statements before continuing? [duplicate]

This question already has answers here:
Does javascript use optimization in boolean expressions? [duplicate]
(3 answers)
Closed 8 years ago.
In Javascript, specifically Google's V8 engine, does writing multiple function calls in a list of or conditions '||' execute all of the functions before determining the final result of the if comparison?
e.g.
var path = 'C:\\MyFiles\\file.doc';
if ( path.match(/\.docx?/gi)
|| path.match(/\.xlsx?/gi)
|| path.match(/\.xml/gi)
|| path.match(/\.sql?/gi)) {
// Success
} else {
// Failed
}
So I would like to ask: Is this similar† to how the '&&' conditions work, but the opposite? Will the first condition evaluating to TRUE cause the remaining to be skipped and the Success logic to be executed?
I cannot find this stated in any documentation that I am looking for. It is not like this will make a huge difference, however I am curious as to how this is actually executing.
†(By similar to the And '&&' I mean that the first condition evaluating to FALSE will stop the remaining conditions from executing and proceed to following else.)
You're right. It's called short circuit evaluation, and it applies to both || and &&.
For ||, evaluation of the right hand side takes place only if the left hand side evaluates to false.
For &&, evaluation of the right hand side takes place only if the left hand side evaluates to true.
Note that it's not just for performance. It also prevents errors from occurring: sometimes evaluating the right hand side would be unsafe or meaningless if the left hand side were not as expected.

difference between if (!!variable), and, if (variable)? [duplicate]

This question already has answers here:
Can someone explain this 'double negative' trick? [duplicate]
(9 answers)
Closed 9 years ago.
Is there any difference (in JS) between using the double negative !! and not using it at all?
For example
if (!!variable){... vs. if (variable){...
I know there are times where I've gotten a warning using the 2nd method..
When should each be used? and when will each throw a warning in the console? (for variables, objects, arrays etc.)
Thanks!!
There is a difference for assigning it, but not for using it in a conditional statement. The reason the !! is used is because the first ! will convert your variable to its truthy evaluation and then not it. So "hello" becomes true, is then negated, becomes false, and the second ! will negate the false, resulting in true. This can be desirable when trying to obtain the thruthy value from a variable. However, there is not much gained by doing it in an if statement.
In this particular case, there is no difference. In fact, !!variable is wasteful.
However in more general cases, it casts the variable to a boolean. Personally I've only found this useful when debugging, and to learn what values are truthy and falsy.

what does the "||" in a var statement mean? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
null coalescing operator for javascript?
What does “options = options || {}” mean in Javascript?
Can someone explain me this expression? I stumbled accros the javascript line of code and I wondered what it means.
var node = element.node || element[element.length - 1].node;
node get's used like this below:
if (node.nextSibling) {
node.parentNode.insertBefore(this.node, node.nextSibling);
} else {
node.parentNode[appendChild](this.node);
}
At first i though node should be a boolean or something but it's not.
Am I correct if i think that the meaning is: node is element.node but if the node attribute is undefined node is the last element in the array of element?
Your understanding is along the right lines; be aware that even if element.node is defined, but is a falsey value (0, false etc.) that element[element.length - 1].node will be assigned to node instead.
It means, if element.node has a value represents True in boolean expressions, node will be element.node, otherwise it will be element[element.length - 1].node
Simple answer: it means OR :)
Reference: http://www.w3schools.com/js/js_operators.asp
It means OR
for example:
if this || that
means "if this or that"
So when the computer comes to the "||" part of your code, if the statement before it is true, it will stop reading that if statement and automatically execute the code underneath.
If the item before that "||" is false, then it will check the next one, and so on...

Categories

Resources