Loops and iteration Flashcards
What is a loop in JavaScript
A loop in JavaScript is a control flow structure that is used to repeatedly execute a block of code while a certain condition is true
. There are several types of loops in JavaScript, including for
, while
, and do...while
loops.
- A
for
loop runs a block of code a specific number of times. It is defined with an initializer, a condition, and an increment or decrement expression. - A
while
loop continues running as long as its condition istrue
. - A
do...while
loop will first execute the code block once, then continue executing it as long as the condition istrue
.
These loops are used to iterate over data structures like arrays and objects, carry out repetitive tasks, or create complex animations and interactions in web applications.
“Loops and iteration - JavaScript | MDN” (developer.mozilla.org). Retrieved July 26, 2023.
for
loop statement
A for
loop repeats until a specified condition evaluates to false
. The JavaScript for loop is similar to the Java and C for
loop.
A for statement looks as follows:
for (initialization; condition; afterthought) statement
When a for 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 condition expression is evaluated. If the value of condition is true, the loop statements execute. Otherwise, the for loop terminates. (If the condition expression is omitted entirely, the condition is assumed to be
true
.) - The statement executes. To execute multiple statements, use a block statement (
{ }
) to group those statements. - If present, the update expression afterthought is executed.
- Control returns to Step 2.
Example:
for (let i = 0; i < 5; i++) { console.log(i); }
“for statement” (developer.mozilla.org). Retrieved July 26, 2023.
while
loop statement
A while
statement executes its statements as long as a specified condition evaluates to true
. A while statement looks as follows:
while (condition) statement
If the condition becomes false
, statement within the loop stops executing and control passes to the statement following the loop.
To execute multiple statements, use a block statement ({ }
) to group those statements.
Example:
let n = 0; let x = 0; while (n < 3) { n++; x += n; }
“while statement” (developer.mozilla.org). Retrieved July 26, 2023.
do...while
loop statement
The do...while
statement repeats until a specified condition evaluates to false
.
A do...while
statement looks as follows:
do statement while (condition);
statement is always executed once before the condition is checked. (To execute multiple statements, use a block statement ({ }
) to group those statements.)
If condition is true
, the statement executes again. At the end of every execution, the condition is checked. When the condition is false
, execution stops, and control passes to the statement following do...while
.
Example:
let i = 0; do { i += 1; console.log(i); } while (i < 5);
“do…while statement” (developer.mozilla.org). Retrieved July 26, 2023.
What is a labeled statement?
A label
provides a statement with an identifier that lets you refer to it elsewhere in your program. For example, you can use a label to identify a loop, and then use the break
or continue
statements to indicate whether a program should interrupt the loop or continue its execution.
The syntax of the labeled statement looks like the following:
label: statement
The value of label
may be any JavaScript identifier that is not a reserved word. The statement that you identify with a label
may be any statement.
Note that JavaScript has no goto
statement; you can only use labels with break
or continue
.
Any break
or continue
that references label must be contained within the statement that’s labeled by label. Think about label as a variable that’s only available in the scope of statement
If a break label;
statement is encountered when executing statement, execution of the labeled statement terminates, and execution continues at the statement immediately following the labeled statement.
continue label;
can only be used if statement is one of the looping statements. If a continue label;
statement is encountered when executing statement, execution of statement continues at the next iteration of the loop. continue;
without a label can only continue the innermost loop, while continue label;
allows continuing any given loop even when the statement is nested within other loops.
A statement can have multiple labels. In this case, the labels are all functionally equivalent.
“label - JavaScript | MDN” (developer.mozilla.org). Retrieved July 31, 2023.
break
statement
Use the break
statement to terminate a loop, switch, or in conjunction with a labeled statement.
When you use break
without a label, it terminates the innermost enclosing while
, do-while
, for
, or switch
immediately and transfers control to the following statement.
When you use break with a label, it terminates the specified labeled statement.
The syntax of the break 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 the index of an element whose value is theValue:
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; } } }
“break statement” (developer.mozilla.org). Retrieved July 31, 2023.
continue
statement
The continue
statement can be used to restart a while
, do-while
, for
, or label
statement.
When you use continue without a label, it terminates the current iteration of the innermost enclosing while
, do-while
, or for
statement and continues execution of the loop with the next iteration. In contrast to the break
statement, continue
does not terminate the execution of the labeled loop statement entirely. In a while
loop, it jumps back to the condition. In a for
loop, it jumps to the increment-expression.
When you use continue
with a label, it applies to the looping statement identified with that label.
The syntax of the continue
statement looks like the following:
continue; continue label;
Example:
The following example shows a while loop with a continue statement that executes when the value of i is 3. Thus, n takes on the values 1, 3, 7, and 12.
let i = 0; let n = 0; while (i < 5) { i++; if (i === 3) { continue; } n += i; console.log(n); } //1,3,7,12
“continue statement” (developer.mozilla.org). Retrieved July 31, 2023.
for...in
loop statement
The for...in
statement iterates over all enumerable string properties of an object (ignoring properties keyed by symbols), including inherited enumerable properties.
Syntax
for (variable in object) statement
Example:
const object = { a: 1, b: 2, c: 3 }; for (const property in object) { console.log(`${property}: ${object[property]}`); } // Expected output: // "a: 1" // "b: 2" // "c: 3"
Note: Many JavaScript style guides and linters recommend against the use of for...in
, because it iterates over the entire prototype chain which is rarely what one wants, and may be a confusion with the more widely-used for...of
loop. for...in
is most practically used for debugging purposes, being an easy way to check the properties of an object
“for…in statement” (developer.mozilla.org). Retrieved August 4, 2023.
How can you loop over the own properties of an object using the for...in
statement?
using Object.hasOwn() the inherited properties are not displayed.
const triangle = { a: 1, b: 2, c: 3 }; function ColoredTriangle() { this.color = "red"; } ColoredTriangle.prototype = triangle; const obj = new ColoredTriangle(); for (const prop in obj) { if (Object.hasOwn(obj, prop)) { console.log(`obj.${prop} = ${obj[prop]}`); } } // Logs: // "obj.color = red"): the inherited properties are not displayed.
“Iterating own properties” (developer.mozilla.org). Retrieved August 4, 2023.
for...of
loop statement
The for...of
statement executes a loop that operates on a sequence of values sourced from an iterable object. Iterable objects include instances of built-ins such as Array
, String
, TypedArray
, Map
, Set
, NodeList
(and other DOM collections), as well as the arguments object, generators produced by generator functions, and user-defined iterables.
Syntax
for (variable of object) statement
Example:
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 7
Note: Each iteration creates a new variable. Reassigning the variable inside the loop body does not affect the original value in the iterable (an array, in this case).
“for…of - JavaScript | MDN” (developer.mozilla.org). Retrieved August 4, 2023.