C.Ronaldo
C.Ronaldo

Reputation: 613

While loop inside a for loop not working

I tried to use a while loop inside a for loop, but everytime when I try do this my browser crashes. I know this happens when the loop is infinite, but I can't seem to figure out why.

for(i=0;i < 2; i++)
{
  console.log("hello");
  while(i < 2)
  {
    console.log("it's me");
  }
}

Upvotes: 0

Views: 297

Answers (4)

user7750452
user7750452

Reputation:

The problem is the while loop, once i becomes 0, it will never come out of the while loop.(Since it is less than 2)

Possible solutions:

SOLUTION 1: Remove the while loop present inside the for loop

SOLUTION 2: Handle inside the while, and break after doing something

     for(i=0;i < 2; i++)
        {
          console.log("hello");
          while(i < 2)
          {
            console.log("i  < 2");
            break;
          }
        }

SOLUTION 3: Change the value of i >=2 inside the while loop, so that, the loop breaks

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386550

You loop the while loop forever, because i keeps the value and is never changed inside.

I think you might use better an if statement to get the additional output.

var i;
for (i = 0; i < 2; i++) {
    console.log("hello");
    if (i < 2) {
        console.log("it's me");
    }
}

Upvotes: 3

Dinesh Devkota
Dinesh Devkota

Reputation: 1417

   for(i=0;i < 2; i++)
    {
      console.log("hello");
      while(i < 2)
      {
     //Once this block is entered, value of i is never changed and the condition
     //is always true.
        console.log("it's me");
      }
    }

Change it to something like the following using secon variable if you want to loop in the while section.

 for(i=0;i < 2; i++)
        {
          console.log("hello");
           j=0;
          while(j < 2)
          {
          j++;
            console.log("it's me");
          }
      }

Upvotes: 0

dav
dav

Reputation: 375

What's happening is your while loop is never ending; the value of i never changes inside the loop, so the loop continues forever.

Maybe what you were looking to do was log the message "it's me" when i, in the for loop, was < 2. In that case, you can use a simple if statement, such that your code reads something like this:

for(var i=0;i<2;i++){
 console.log("hello");
 if(i<2) console.log("it's me");
}

I'd recommend playing around with the number values and testing it out to get a better feel for how JS syntax works.

Upvotes: 1

Related Questions