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.
Related
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.
The continue statement in javascript doesn't really make sense to me, or am I over thinking this?
For example, let's say I am for inning inside an object:
for (i in JM) {
if (JM[i].event == 'StartLocation') {
continue;
}
}
If that if statement is true, it's going to technically hop over that iteration. Why do we use the word continue then? Wouldn't it make more sense to use the word break? But, break does the total opposite, it stops the loop, right? (Or maybe a statement called hop) would make sense. Never really thought of this until a couple minutes ago :P
Yes, break takes you out of the loop and places you at the line after the loop. continue takes you directly back to the start of the next iteration of the loop, skipping over any lines left in the loop.
for(i in JM)
{ // continue takes you directly here
if(JM[i].event=='StartLocation'){
continue;
}
// some other code
} // break takes you directly here
If you're only asking about the word choice, then there probably isn't a great answer to this question. Using continue does cause loop iteration to continue, just on the next iteration. Any keyword could have been chosen. The first person to specify a language with this behavior just chose the word "continue."
The continue keyword is similar to break, in that it influences the progress
of a loop. When continue is encountered in a loop body, control jumps
out of the body and continues with the loop’s next iteration.
Understand it like this:
for(i in JM){
if(JM[i].event=='StartLocation'){
continue;
}
/*This code won't executed if the if statement is true and instead will move to next iteration*/
var testCode = 3;// Dummy code
}
break will break the for loop(come out of for loop) but continue will skip the current iteration and will move to next iteration.
You will find the relevant docs Here.
While reading code from a JS Editor (Tern), I have come across various uses for the for-loop as seen in the snippets below:
code snippet 1 # lines 463-468:
for (;;) {
/* some code */
}
code snippet 2 # lines 97-100
for (var i = 0; ; ++i) {
/* some code */
}
On the same note, I also have come across a for-loop with an empty body e.g:
for (var p; p; p = someValue) /* empty body */ ;
I am trying to understand what happens in code execution flow.
My take is that for code in snippet 1, the for loop has no conditions, so it may continue endlessly? For code in snippet 2, i is continually incremented without a limit? For the third one, the loop continues till p is assigned something that evaluates to false?
These are the ideas I have in my mind yet I am not sure. Please assist.
In Short
First of all you are correct in all your assertions.
The first loop runs until it is exited from abruptly (with a break, return, throw etc..).
The second loop runs until it is exited from abruptly but also performs a variable assignment, and increments a value.
The third for loop runs like a normal for loop until the center condition is falsey. Its body is empty.
But Why does JavaScript do this?
Let's dig into why this happens.
If we take a closer look at the language specification we can see that the following happens in a for loop:
IterationStatement : for ( ExpressionNoIn(opt) ; Expression(opt) ; Expression(opt)) Statement
I will treat these statements and that definition for the rest of the answer.
Now let's go through the cases.
In case one of for(;;) the following happens:
ExpressionNoIn is not present, so nothing is called for that clause (As clause 1 states).
The second expression is not in, so we do not return calls (as clause 3 states).
The third expression is empty so no "incremenetion" is performed (as clause 3.f states).
So it would basically repeat endlessly just as you predicted (until broken from with a break or returned from, or thrown from and generally anything that causes abrupt completion). (As clauses e and d tell us).
In the second case for (var i = 0; ; ++i) the following happens:
ExpressionNoIn is present, so we evaluate it, and assign it with get value (as clause 1 states). We do not assign it.
Then we repeat endlessly since the second expression is not here. So we continue until abrubt execution happens or a break happens. More specifically this is defined here.
We increment i on every iteration as clause f states.
In the third case for (var p; p; p = someValue) /* empty body */ ; the following happens:
This evaluates as a for loop. Statement is empty indeed but the for loop does not really care. The only difference is that no value is returned from the for loop. Basically it's a full and legal for loop. ; is simply an empty statement. It is useful when you want to run a for loop with no content in the actual loop. You see this sometimes in feature detection. This is also useful when you want to find the minimum n such that... .
You are correct in that it runs until the value is falsey, or more accurately calling ToBoolean on it produces false. As clause 3.a.ii specifies.
As you can see, this is all in the spec and well defined :)
Why do coders do this?
In the first snippet the perform their flow control with a break clause. if (eol >= pos || eol < 0) break; (they check for the end of line, and this could be done in a more conventional for loop).
In the second snippet again they do flow control using break:
if (!definitions.hasOwnProperty(uniq)) { name = uniq; break; }
They again put it in a break statement inside the for loop.
The third snippet is out of context, but let's say we want to (trivial example) find the first number bigger than 10 (or the 10th div element, or occurance of a string - you get the idea). We could do :
for(var i=0;i<=10;i++);
And get the first number bigger than 10.
You are correct in your understanding.
The first snippet is an infinite loop; there is no termination condition, so the loop will (in itself) continue forever. This is almost certainly accompanied by a break statement somewhere within the body, which will exit the loop when it is run. (The other option is that a thrown exception exits the loop, although it is bad practice to use exceptions as control flow.) This pattern (or an equivalent while (true) {...} ) usually occurs when the exit condition is too complex to express within the loop statement.
The second snippet is similar to the first, in that without a termination condition it will run forever. This will also require a break statement (or exception) to terminate the loop. The only difference here is that a counter variable is also being incremented on each iteration.
The third snippet is a loop with no body, though the test and variable update happen on each iteration of the loop. As you expected, this continues until p evaluates to false. This for loop is exactly equivalent to the while loop version:
var p;
while (p) {
p = someValue;
}
which perhaps makes it clearer that the assignment happens repeatedly until !p.
MDN states:
When you use continue without a label, it terminates the current iteration of the innermost enclosing while, do-while or for statement and continues execution of the loop with the next iteration.
I'm not sure why the following piece of code does not work as I expect.
do {
continue;
} while(false);
Even though the while condition is false, I expect it to run forever since continue jumps towards the start of the block, which immediately executes continue again, etc. Somehow however, the loop terminates after one iteration. It looks like continue is ignored.
How does continue in a do-while loop work?
Check out this jsFiddle: http://jsfiddle.net/YdpJ2/3/
var getFalse = function() {
alert("Called getFalse!");
return false;
};
do {
continue;
alert("Past the continue? That's impossible.");
} while( getFalse() );
It appears to hit the continue, then break out of that iteration to run the check condition. Since the condition is false, it terminates.
continue does not skip the check while(false) but simply ignores the rest of the code within the brackets.
Continue stops execution of the rest of the code in the block and jumps directly to the next iteration of your loop.
Since you are doing while(false) there is no next iteration
continue doesn't start over the current iteration again but skips to the next one (as said in the MDN-quote).
because of a false condition, there is no next iteration - so the whole loop is completed.
I expect it to run forever since continue jumps towards the start of
the block
The continue doesn't jump to the start of the block, it jumps to the end of the block.
After the continue, the loop conditional is evaluated, since it is false, the loop will terminate.
Use while(true) to get an infinite loop.
If you replaced while(false) with while(true), you would get an infinite loop.
do {
continue;
} while(true);
continue skips to the end of the block, which in a do-while loop, will execute the conditional statement.
In your case, your condition was false and therefore it terminates the loop. If that condition is true, it would continue at the start of the loop.
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.