I am learning the do-while loop and am unable to understand why this loop is running infinitely.
var condition = true
var getToDaChoppa = function(){
do {
console.log("I'm the do loop");
} while(condition === true){
console.log("I'm the while loop");
condition = false;
};
};
getToDaChoppa();
I am learning the do-while loop and am unable to understand why this loop is running infinitely.
var condition = true
var getToDaChoppa = function(){
do {
console.log("I'm the do loop");
} while(condition === true){
console.log("I'm the while loop");
condition = false;
};
};
getToDaChoppa();
Share
Improve this question
asked Mar 26, 2016 at 21:00
Syed Arafat QureshiSyed Arafat Qureshi
1473 silver badges13 bronze badges
1
-
5
The loop starts with the
do
and ends with thewhile
, and nothing in between changes thecondition
. The block after it is just a separate block. – user1106925 Commented Mar 26, 2016 at 21:02
3 Answers
Reset to default 3You never set the condition
variable to false
INSIDE the loop, so it will never execute any of your code outside of the loop until this loop has pleted (which will never happen given your current example). Make sure that you set the condition
variable to false
inside the loop:
do {
console.log("I'm the do loop");
if (some_condition_is_met) {
condition = false;
}
} while(condition === true);
Do/While works like this. So you never change the condition
inside the loop.
do {
//code block to be executed
}
while (condition);
//Code after do/while
There is a do..while
and there is a while..
: there is no do..while..
statement.
JavaScript allows block statements independent of other flow-control/definition constructs. Due to lack-of-a-required statement semicolon this does not result in a syntax error (it would in Java).
Here is some additional clarification relating to the syntax; other answers cover the logical error.
do {
console.log("I'm the do loop");
} while(condition === true) // semicolons optional in JS (see ASI):
// 'do..while' statement ENDS HERE
{ // starts a block statement which has naught to do with 'do..while' above
// THERE IS NO WHILE LOOP HERE
console.log("I'm the while loop");
condition = false;
}; // useless semicolon which further leads to confusion
On the other hand, if the do..
was omitted it would have been parsed as "just" a while
statement which would have terminated.
// Basic WHILE statement - no 'do..' code, so NOT parsed as a 'do..while'!
while(condition === true)
{ // this block is now part of the 'while' statement loop
console.log("I'm the while loop");
condition = false;
};
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745318555a4622334.html
评论列表(0条)