


In this condition, the execution process finally terminates.įollowing is the syntax used for while loop in JavaScript code: while (expression needed to be executed) while (expression needed to be executed) Īlways remember to use semicolons at the end of the statements after defining them.įollowing is an example of a JavaScript code using above mentioned do…while loop: ĭocument. They are basic loops that carry out the execution of the statements defined under it or the code block written under it, the execution process carries out in a loop until the expression values out to be false.

You can use while loops to execute statements that are repeated continuously in JavaScript code. The syntax is: While( condition, body ) For example, here are two different programs that use a While() loop to find the least power of 2 that is greater than or equal to x (287). The trouble of writing the same JavaScript code can be eliminated by using loops.įollowing are the loops supposed by JavaScript: A related function is While(), which repeatedly tests the condition and evaluates its body script as long as the condition is true. To execute such actions, you must write the code repeatedly until you achieve the number for which you want to perform the loop. The first time the code runs, it will be executed and display 0, but then it will check the condition and stop from running again.There are situations while programming when there is a need to perform a certain action again and again or, let's say, in a continuous loop. In the following example, you can see how in the first loop, the condition is i < -1, but the starting count number is 0, so the condition of the loop is false. Also while loop should be the de-facto choice for an infinite loop (I don't see a reason why you would have an infinite loop in javascript, though). As long as the condition evaluates to true. For example when you are dealing with an external condition (the variable you are checking is defined outside the loop), go with a while loop. It consists of a condition and the statement block. Therefore, it is always run at least once before checking whether the condition is met or not. The JavaScript while loop is much simpler than the for loop. In the syntax snippet above, you can see the main difference from the usual JavaScript while loop: in this case, the condition is defined after the code to be executed.

Then, it will check the condition, and continue to loop again if it is actually true. The JavaScript do while loop is different from while loop: using do while loop JavaScript always executes the code at least once - even if the condition is false.
