Loops and iteration
Loops offer a quick and easy way to do something repeatedly. Thischapter of theJavaScript Guideintroduces the different iteration statements available to JavaScript.
You can think of a loop as a computerized version of the game where you tell someone totakeX steps in one direction, thenY steps in another. For example,the idea "Go five steps to the east" could be expressed this way as a loop:
for (let step = 0; step < 5; step++) { // Runs 5 times, with values of step 0 through 4. console.log("Walking east one step");}There are many different kinds of loops, but they all essentially do the same thing:they repeat an action some number of times. (Note that it's possible that number couldbe zero!)
The various loop mechanisms offer different ways to determine the start and end pointsof the loop. There are various situations that are more easily served by one type ofloop over the others.
The statements for loops provided in JavaScript are:
In this article
for statement
Afor loop repeats until a specified condition evaluates to false. The JavaScriptfor loop is similar to the Java and Cfor loop.
Afor statement looks as follows:
for (initialization; condition; afterthought) statementWhen afor loop executes, the following occurs:
- The initializing expression
initialization, if any, is executed. This expression usually initializes one or more loop counters, but the syntax allows an expression of any degree of complexity. This expression can also declare variables. - The
conditionexpression is evaluated. If the value ofconditionis true, the loop statements execute. Otherwise, theforloop terminates. (If theconditionexpression is omitted entirely, the condition is assumed to be true.) - The
statementexecutes. To execute multiple statements, use ablock statement ({ }) to group those statements. - If present, the update expression
afterthoughtis executed. - Control returns to Step 2.
Example
In the example below, the function contains afor statement that countsthe number of selected options in a scrolling list (a<select>element that allows multiple selections).
HTML
<form name="selectForm"> <label for="musicTypes" >Choose some music types, then click the button below:</label > <select name="musicTypes" multiple> <option selected>R&B</option> <option>Jazz</option> <option>Blues</option> <option>New Age</option> <option>Classical</option> <option>Opera</option> </select> <button type="button">How many are selected?</button></form>JavaScript
Here, thefor statement declares the variablei and initializes it to0. It checks thati is less than the number of options in the<select> element, performs the succeedingif statement, and incrementsi by 1 after each pass through the loop.
function countSelected(selectObject) { let numberSelected = 0; for (let i = 0; i < selectObject.options.length; i++) { if (selectObject.options[i].selected) { numberSelected++; } } return numberSelected;}const btn = document.getElementById("btn");btn.addEventListener("click", () => { const musicTypes = document.selectForm.musicTypes; console.log(`You have selected ${countSelected(musicTypes)} option(s).`);});do...while statement
Thedo...while statement repeats until aspecified condition evaluates to false.
Ado...while statement looks as follows:
do statementwhile (condition);statement is always executed once before the condition ischecked. (To execute multiple statements, use a block statement ({ })to group those statements.)
Ifcondition istrue, the statement executes again. At theend of every execution, the condition is checked. When the condition isfalse, execution stops, and control passes to the statement followingdo...while.
Example
In the following example, thedo loop iterates at least once andreiterates untili is no longer less than5.
let i = 0;do { i += 1; console.log(i);} while (i < 5);while statement
Awhile statement executes its statements as long as aspecified condition evaluates totrue. Awhile statement looksas follows:
while (condition) statementIf thecondition becomesfalse,statement within the loop stops executing and control passes to thestatement following the loop.
The condition test occursbeforestatement in the loop isexecuted. If the condition returnstrue,statement is executedand thecondition is tested again. If the condition returnsfalse, execution stops, and control is passed to the statement followingwhile.
To execute multiple statements, use a block statement ({ }) to groupthose statements.
Example 1
The followingwhile loop iterates as long asn isless than3:
let n = 0;let x = 0;while (n < 3) { n++; x += n;}With each iteration, the loop incrementsn and adds that value tox. Therefore,x andn take on the followingvalues:
- After the first pass:
n=1andx=1 - After the second pass:
n=2andx=3 - After the third pass:
n=3andx=6
After completing the third pass, the conditionn < 3 is no longertrue, so the loop terminates.
Example 2
Avoid infinite loops. Make sure the condition in a loop eventually becomesfalse—otherwise, the loop will never terminate! The statements in thefollowingwhile loop execute forever because the condition never becomesfalse:
// Infinite loops are bad!while (true) { console.log("Hello, world!");}labeled statement
Alabel provides a statement with an identifier thatlets you refer to it elsewhere in your program. For example, you can use a label toidentify a loop, and then use thebreak orcontinue statementsto indicate whether a program should interrupt the loop or continue its execution.
The syntax of the labeled statement looks like the following:
label: statementThe value oflabel may be any JavaScript identifier that is not areserved word. Thestatement that you identify with a label may beany statement. For examples of using labeled statements, see the examples ofbreak andcontinue below.
break statement
Use thebreak statement to terminate a loop,switch, or in conjunction with a labeled statement.
- When you use
breakwithout a label, it terminates the innermostenclosingwhile,do-while,for, orswitchimmediately and transfers control to the following statement. - When you use
breakwith a label, it terminates the specified labeledstatement.
The syntax of thebreak statement looks like this:
break;break label;- The first form of the syntax terminates the innermost enclosing loop or
switch. - The second form of the syntax terminates the specified enclosing labeled statement.
Example 1
The following example iterates through the elements in an array until it finds theindex of an element whose value istheValue:
for (let i = 0; i < a.length; i++) { if (a[i] === theValue) { break; }}Example 2: Breaking to a label
let x = 0;let z = 0;labelCancelLoops: while (true) { console.log("Outer loops:", x); x += 1; z = 1; while (true) { console.log("Inner loops:", z); z += 1; if (z === 10 && x === 10) { break labelCancelLoops; } else if (z === 10) { break; } }}continue statement
Thecontinue statement can be used to restart awhile,do-while,for, orlabelstatement.
- When you use
continuewithout a label, it terminates the currentiteration of the innermost enclosingwhile,do-while, orforstatement and continues execution of the loop with the nextiteration. In contrast to thebreakstatement,continuedoesnot terminate the execution of the loop entirely. In awhileloop, itjumps back to the condition. In aforloop, it jumps to theincrement-expression. - When you use
continuewith a label, it applies to the looping statementidentified with that label.
The syntax of thecontinue statement looks like the following:
continue;continue label;Example 1
The following example shows awhile loop with acontinuestatement that executes when the value ofi is3. Thus,n takes on the values1,3,7, and12.
let i = 0;let n = 0;while (i < 5) { i++; if (i === 3) { continue; } n += i; console.log(n);}// Logs:// 1 3 7 12If you comment out thecontinue;, the loop would run till the end and you would see1,3,6,10,15.
Example 2
A statement labeledcheckIandJ contains a statement labeledcheckJ. Ifcontinue is encountered, the programterminates the current iteration ofcheckJ and begins the nextiteration. Each timecontinue is encountered,checkJreiterates until its condition returnsfalse. Whenfalse isreturned, the remainder of thecheckIandJ statement is completed,andcheckIandJ reiterates until its condition returnsfalse. Whenfalse is returned, the program continues at thestatement followingcheckIandJ.
Ifcontinue had a label ofcheckIandJ, the programwould continue at the top of thecheckIandJ statement.
let i = 0;let j = 10;checkIandJ: while (i < 4) { console.log(i); i += 1; checkJ: while (j > 4) { console.log(j); j -= 1; if (j % 2 === 0) { continue; } console.log(j, "is odd."); } console.log("i =", i); console.log("j =", j);}for...in statement
Thefor...in statement iterates a specifiedvariable over all the enumerable properties of an object. For each distinct property,JavaScript executes the specified statements. Afor...in statement looks asfollows:
for (variable in object) statementExample
The following function takes as its argument an object and the object's name. It theniterates over all the object's properties and returns a string that lists the propertynames and their values.
function dumpProps(obj, objName) { let result = ""; for (const i in obj) { result += `${objName}.${i} = ${obj[i]}<br>`; } result += "<hr>"; return result;}For an objectcar with propertiesmake andmodel,result would be:
car.make = Fordcar.model = Mustang
Arrays
Although it may be tempting to use this as a way to iterate overArrayelements, thefor...in statement will return the name of your user-definedproperties in addition to the numeric indexes.
Therefore, it is better to use a traditionalfor loopwith a numeric index when iterating over arrays, because thefor...instatement iterates over user-defined properties in addition to the array elements, ifyou modify the Array object (such as adding custom properties or methods).
for...of statement
Thefor...of statement creates a loop Iteratingoveriterable objects (includingArray,Map,Set,arguments object and so on), invoking a customiteration hook with statements to be executed for the value of each distinct property.
for (variable of iterable) statementThe following example shows the difference between afor...of loop and afor...in loop. Whilefor...in iteratesover property names,for...of iterates over property values:
const arr = [3, 5, 7];arr.foo = "hello";for (const i in arr) { console.log(i);}// "0" "1" "2" "foo"for (const i of arr) { console.log(i);}// Logs: 3 5 7Thefor...of andfor...in statements can also be used withdestructuring. For example, you can simultaneously loop over the keys and values of an object usingObject.entries().
const obj = { foo: 1, bar: 2 };for (const [key, val] of Object.entries(obj)) { console.log(key, val);}// "foo" 1// "bar" 2