Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While & For-Loops [closed]

I don't understand why this function works as a While-Loop, but not as a For-Loop. I am trying to count to 10 and print to console on each iteration.

While-Loop:

function oneToTenW() {
  var x = 0;
  while(x < 10) {
    x++;
    console.log ("x is equal to " + x);
  }
}

For-Loop:

function oneToTenF() {
  for(var x = 0; x < 10; x++);
  console.log ("x is equal to " + x);
}

When I call the While-Loop, I get this:

oneToTen();
x is equal to 1
x is equal to 2
x is equal to 3
x is equal to 4
x is equal to 5
x is equal to 6
x is equal to 7
x is equal to 8
x is equal to 9
x is equal to 10

Whereas when I call the For-Loop, I get this:

oneToTenf();
x is equal to 10

Any thoughts?

like image 977
Padawan Avatar asked Feb 18 '26 14:02

Padawan


1 Answers

This line right here:

for(var x = 0; x < 10; x++);

Because you have a semicolon at the end, the statement effectively terminates there, and the loop executes without doing anything. To have the loop execute the statement below it, you need to include that statement in the loop body, by removing the semicolon:

for(var x = 0; x < 10; x++)
  console.log ("x is equal to " + x); // <- the line immediately after the for statement will be executed on every iteration

Or by enclosing the statement or statements to be executed in a block (braces):

for(var x = 0; x < 10; x++) {
  console.log ("x is equal to " + x);
}

Now the statement will be executed every time that the loop iterates.

like image 73
ElGavilan Avatar answered Feb 21 '26 04:02

ElGavilan