plematic.blogg.se

While loop javascript
While loop javascript








The break statements can be combined with other statements such as the conditional if statements to terminate the loop from inside its body once a specific condition is met.įor our next example we will take the code from our first example and modify it so the loop breaks if there is a multiple of ten inside the table of 2. JavaScript gives us the option to use break statements inside the body of the while loops to terminate the loop. How to use break statement with while loop in JavaScript

while loop javascript

The while loop kept iterating and the Math object kept generating random numbers until the condition was met which was a random number greater than 500. Then we used the console.log method to print the randomNumber onto the console. Inside the body of the loop we used the Math object to get a random number between 0 and 999 and assigned this number to the randomNumber variable. We then declared a while loop and gave it a condition which is randomNumber < 500. This was only done because the while loops check the condition before every iteration (on the first iteration the loop ran because the condition was true as 0 < 500).

while loop javascript

In the example given above we first created a variable named randomNumber and assigned it a value 0. In JavaScript, you use a do-while loop when you are not sure how many times you will execute the loop body and the loop body needs to execute at least once.










While loop javascript