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.
Related
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
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 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.
Can anyone tell me why in the following code a do/while lop is used rather than a simple if statement:
function prev(elem){
do {
elem = elem.previousSibling;
} while(elem && elem.nodeType != 1);
return elem;
}
Why not:
function prev(elem){
if(elem && elem.nodeType != 1) {
elem = elem.previousSibling;
return elem;
}
Is there an advantage to using do/while? Thanks!
do-while will run once and continue running while the statement is true, while the if-statement will only run once.
In this instance it may be equivalent (depending on how the code and data is set up), but typically that is how do-whiles are used.
If you want something to keep repeating until a certain condition is met, use the do,for, or while statement. If you only want to check something once, use the if statement.
If you are using do while loop, then your statements will execute atleast once. Then a condition is checked and if the condition is not satisfied then the statement are not executed any more. But if you use the other option then first condition is checked and if the condition is satisfied then the statements are executed only once. Otherwise they are not executed even a single time.
A While or Do While statement is a continuous loop until a condition is met.
An If, Then, Else/Else If is a simple evaluative statement rather than a loop.
Here do-while will run atleast once, and will execute until while condition is met.
But in the if-statement, it'll check the condition first, and will execute once only and will return the response.
I'm new to javascript and am having issues with a seemingly simple if/else statement.
Can anyone let me know why the below isn't working please (Im pulling my hair out)
var is_expanded = false;
if (is_expanded==false) {
alert('no');
is_expanded = true;
} else {
alert('yes');
}
I always get the 'no' alert (I never get to the else part).
Cheers for any help.
This is working as designed.
The condition is checked when you say if. It then goes into the correct block, in this case the one that alerts "no".
The condition does not get re-evaluated after the block has been executed. That's just not how the if statement works, not in any language I know.
Depending on what you want to do, there are other patterns and constructs that can help you, for example a while loop. Maybe show the real use case that you need this for.
That's because is_expanded always equals false because you've set it as false BEFORE the if statement.
else will not fire unless is_expanded equals true before the if statement.
You previous line of code says var is_expanded = false;
which means if (is_expanded==false) will always evaluate to true.
So that is exactly what you are getting as output. What did you expect?
Next time when your same method is called, the value for is_expanded is again reset to false due to your first line of code. Then again it will alert no
That's normal. You have set the variable is_expanded to false so in the if statement you are always entering the alert('no'); part. After you set the variable to true but there is no longer any if statement executed.
var is_expanded = false;
if (is_expanded==false) {
alert('no');
is_expanded = true;
} else {
alert('yes');
}
Congratulations! Your code is working perfectly, so stop pulling your hair out.
The nature of IF/ELSE is that only one of them fires per pass. So, your code checks whether is_expanded is FALSE. If it's false, it will run the IF part. If not, it'll run the ELSE part.
Just read it like english.
If something, do this. Otherwise, do something else
Even if you change the value of the variable inside one of the blocks, it won't matter because once it checks the block, it moves on.