Loops help you to perform some repetitive task in succession and are often based on the fulfilment of a condition.
In scenarios where we need to perform a repeated operation, writing the repetitive code for every action makes the code redundant and unreadable. Loops are used to keep the code concise and readable wherever there is a need to perform some repeated operations.
So you saw how complicated situations can be broken down into a series of smaller repeated tasks. Let’s now understand how to write these loops in JavaScript.
while Loop:
while loop is used to create a loop which will be executed as long as a specific statement holds true, which is specified inside the while loop itself.
Syntax:
while (condition) { /* body code along with statement(s) terminating of the condition at some point in future */ }
Example:
var num = 1234; var sum = 0, n = num; while (n > 0) { sum += (n % 10); n = Math.floor(n / 10); } console.log("Sum of the digits of " + num + " = " + sum);
Output:
"Sum of the digits of 1234 = 10"