Code not working as expected!


#1


https://www.codecademy.com/en/courses/javascript-beginner-en-ASGIv/2/4?curriculum_id=506324b3a7dffd00020bf661


The code is accepted in the editor. but logically it shouldn't! Why is the for loop executed when condition is false?! shouldn't only the do be executed. plus when i change condition to true, it becomes an infinite loop?! i did define the variable as a false again in the while loop? pls explain thanks in advance


var condition= false;
do {
    console.log("I am loggin do");
} while (condition) {
    for (i = 0; i < 5; i++){
        console.log("for loop");
    }
    condition=false;
}


#2

Point1.
do while simply runs at least one time and prints "I am loggin do".

Point2.
This tho is just different code block and independent of do..while clause.

{
    for (i = 0; i < 5; i++){
        console.log("for loop");
    }
    condition=false;
}

As it's for loop, that iterate 5 times, It prints "for loop",
Then you set condition's value to false (It has no impact on loops in code),

I think you confused that for loop is part of do..while ?
do..while's body starts after do, while carries the condition.
as condition comes after body of do..while so it runs at least once.


#3

The interpreter actually sees your code like this:

var condition = false;
do {
    console.log("I am logging do");
} while (condition)
{
    for (var i = 0; i < 5; i++) {
      console.log("for loop");
    }
    condition = false;
}

You can define a new block at anytime like this:

{
    var everything = "everything";
}

and that's perfectly legal.

The log in the do portion always executes once, that's what a do..while does. However, when you initialized the condition to true, it was never able to leave the do...while to reach the condition = false line.

Tricky stuff, hope this helps.


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.