10/13/2023 0 Comments For while javascript![]() To avoid such situations, my humble advice is to write the updation statement right after starting the statement block. It’s a common error by beginners to forget the updation statement in which case the condition will never evaluate to ‘false’ and this will result in an infinite loop. The condition lies between the parenthesis and the updation statement ( x++) is present inside the statement block. Note that the initialization statement ( X = 1) has been placed before the loop. We’ll now employ the while loop to do the same thing. In the previous session, we had used the for loop to display digits 1 to 10 in an alert box. It consists of a condition and the statement block.Īs long as the condition evaluates to ‘true’, the program execution will continues to loop through the statements. 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.The JavaScript while loop is much simpler than the for loop. 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 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). ![]() In the example given above we first created a variable named randomNumber and assigned it a value 0. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |