Does an "if" statement with multiple "or" operators exit when the first condition returns true, or are all conditions evaluated?
i.e. does the order of your conditions matter?
Example scenario:
A shouldComponentUpdate() function with an if statement and the evaluated conditions vary in cost.
Does the order of the conditions (with the least expensive first) promise an improvement in performance or will the entire if statement get evaluated even if the first condition will return a true?
For example:
Assume an if statement in the form:
if ( (this.props.value != nextProps.value) || (deepDiffer(object1, object2) )
If (this.props.value != nextProps.value) returns true, will the code still evaluate the deepDiffer? Or will it immediately enter the if statement and execute the conditional code?
This is Javascript, so yes, it exits when the first condition is true.
According to MDN:
As logical expressions are evaluated left to right, they are tested
for possible "short-circuit" evaluation using the following rules:
false && anything is short-circuit evaluated to false.
true || anything is short-circuit evaluated to true.
The rules of logic guarantee that these evaluations are always correct. Note that the anything part of the above expressions is not evaluated, so any side
effects of doing so do not take effect.
In a condition, if there are multiple 'or', they are checked from left to right and if the first is true, it won't check the nexts.
Same behaviour in a 'and' chain, when the first false is encounter, the nexts won't be checked
This is basic Javascript
Related
I want to check if my message has some data or not and if it has some data it should do required process. How to do this inside if statement in node.js particularly?
Currently I am trying this:
if (messageBody && messageBody.x && messageBody.y && messageBody.z =='true'){
do this
}
But it does not enter the if block and exits.
Conditional statements are not different on a Node.js and a browser environment.
Your conditional statement looks quite strict and that last strict comparison operator messageBody.z == 'true' may need reviewing as you are performing an implicit cast on an equality check over a string literal.
I am currently having a hard time figuring out how to use multiple conditions for my if-else statements. I can do 1 condition at a time, but multiples are a problem for me. I'm not quite sure where to start with the multiple one as I'm using the HTML form stuff, and I'm not sure where to start with it as well. Any sample code is fine as I would like to learn rather than have people figure everything out for me.
Ok, let's start from the beginning.
You agree that this code right here:
if (true)
console.log('foo');
obviously prints out 'foo' on your console, cause the condition is satisfied (i.e. is true).
Let's try something different now:
if (true && false)
console.log('bar');
The && in Javascript and most programming languages is the and operator, which evaluates to true only if both the conditions at its left and at its right are true. This means that the code above does not print out 'bar'.
if (true || false)
console.log('bla');
The || operator, on the other hand, is the or operator, which is true when one of the two conditions (or both) is true. In this case, 'bla' is printed out on your console.
In the end, let's have a look at the ! operator (not): if the condition that follows the operator is true, then it evaluates to false, and viceversa. So writing if (!false) equals if (true).
Now you can apply these simple rules to easily use multiple logical conditions in one if or else branch. Remember the precedence of the logical operators, i.e. which one you have to evaluate first if you have more than one, taking a look here: Which Logic Operator Takes Precedence
I'm interested at what point of time a condition in an if/else statement gets evaluated.
Imagine there's the following sample:
if (complex condition 1) {
do something
}
else if (complex condition 2) {
do something else
}
else if (complex condition 3) {
do something else
}
else {
do anything
}
What I want to know is: does each of the complex conditions get check on ahead of time, and the interpreter just execudes the codepart of the condition that is true, or does it start with the first condition when it comes to it and only evaluates the second condition when the first one is false?
I'm interested in regards to make some optimizations for low-end mobile devices.
The condition clause of an if statement is evaluated when the if statement is reached in the flow of execution. In your example, if the first condition is true, then none of the other conditions will be evaluated.
As "Short-circuit_evaluation" says: "...the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression."
The execution will stop when reach a true statement.
I ran into this piece of code:
<a ng-click= "item.statusId !== itemStatus.in || transfer()">
I guess we can generalize as:
<element ng-click = "someVar !== someValue || doStuff()">
I then found this article on short circuits and another more focused one once I knew what they are called. However, I still don't get it.
Does it basically work on the principle of an OR statement ending evaluation if the first statement evaluates to true? So if the first statement is true, end evaluation, if it's false, run the function in the second half of the OR statement? (This is the main question I am asking, everything else is extra).
I guess that part I don't get is whether the compiler interprets this code differently or it still evaluates to false and just runs the function. Not even sure how to phrase Q.
Does it basically work on the principle of an OR statement ending evaluation if the first statement evaluates to true? So if the first statement is true, end evaluation, if it's false, run the function in the second half of the OR statement?
It's effectively shorthand for an if statement, and you intuited correctly why it works. For more details on short-circuit evaluation in JavaScript, see this Stack Overflow question.
That code is equivalent to:
//Note the intentional and explicit use of `== false` to mean falsy (NOT `=== false` to indicate strict equality test for false)
if( (item.statusId !== itemStatus.in) == false ) {
transfer();
}
It is an interesting means of executing a function only when a condition is falsy.
There are many different examples of this around on StackOverflow, and is not specific to AngularJS.
I was exploring the Google Closure Compiler, and one thing I noticed was that it converts while(true) into for(;;).
Both do hang the browser, but why does the empty for loop not break out of itself immediately? The second part of it is empty, and therefore falsy. Isn't it true that when the second part is falsy, the for loop stops and execution continues with code which comes after the for loop?
Could someone perhaps give an explanation for this?
No, it is not true.
See: https://developer.mozilla.org/en/JavaScript/Reference/Statements/for
condition
An expression to be evaluated before each loop iteration. If this
expression evaluates to true,
statement is executed. This
conditional test is optional. If
omitted, the condition always
evaluates to true. If the expression
evaluates to false, execution skips to
the first expression following the for
construct.
I should perhaps give a link to ECMAScript reference, but I'm pretty sure it states more or less same thing.
From the ECMAScript language specification:
IterationStatement : for (ExpressionNoIn_opt ; Expression_opt ; Expression_opt) Statement
If the first Expression is present, then
Let testExprRef be the result of evaluating the first Expression.
If GetValue(testExprRef) is false, return (normal, V, empty).
Since the first expression (the second argument to for) is not present, this section is never run, so the for loop does not exit.
An empty middle part should be interpreted as true, so it's not falsy. It has the same semantics in C and other languages with that kind of loop (like C#, Java and so on). It would be a real trap to have changed it for JavaScript.
There is evaluation algorothm of for loop in Standard ECMA-262 script that says there are only two situations in which loop will end:
break statement
value of middle statement equal to false, but only if this statement is present, so it doesnt have to be necessary valuated as true (probably in mozilla js engine it is).