Home > database >  Difference in output between While and For loop JavaScript - Newbee
Difference in output between While and For loop JavaScript - Newbee

Time:09-25

It's a basic question; I can't seem to understand why in the code below the while loop output begins with 2 "#" and the for loop start with 1

Console Log Screenshot


let brick = "#";
while (brick.length < 8){

 brick  = "#";
  console.log(brick);
}
console.log("For Loop");
for (let i = "#"; i.length <8; i ="#"){
 console.log(i) 
}

CodePudding user response:

You have already instatiated the brick at the start. But, when you are looping in the for loop the length is increased after the loop is finished. And the opposite is happening in the while loop.

CodePudding user response:

Because in the while loop, you are incrementing before and in the for loop after writing to the console.

Move your brick = "#"; to the end of the while loop and they will behave both the same way:

let brick = "#";

while (brick.length < 8) {
    console.log(brick);
    brick  = "#";
}

For-Loop:

for (let i = "#"; i.length < 8; i  = "#")
                                  ^ happens AFTER each iteration

CodePudding user response:

A for loop

 for (init ; condition ; update) 
    body

is basically a shortcut for this while loop:

 init
 while (condition) {
    body
    update
 }

Now, if you rewrite your for loop according to this pattern

let i = "#"            // init
while (i.length < 8) { // condition
   console.log(i)      // body
   i  = "#"            // update
}

it should be obvious how this is different from your first loop.

  • Related