Thursday, December 19, 2013

JavaScript Tutorial 6 - While Loops

In JavaScript While Loops can execute a block of code as long as a specified condition is true. So as long as your condition is true the block of code will keep looping until your condition is false. They syntax looks like this...

block of code to be looped

This is very simple, now to get a more complex take on while loops, this will look something like this...

var x = 4;

while( x == 4)
x = 5

This code will run the alert statement once, because I added in the x = 5, which makes the condition false and will stop the loop. Its very important to have a way for the condition to become false or else it will create an infinite loop and crash your browser.You can also do something like this...

while (i<5)  {  x=x + "The number is " + i + "<br>";  i++;  }

This code will spit out 5 different alerts by using the "++" statement which just increase the value of a variable by 1. This is the basics of how while loops work in JavaScript.

No comments:

Post a Comment