Loops and iteration Flashcards

1
Q

What is a loop in JavaScript

A

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 is true.
  • A do...while loop will first execute the code block once, then continue executing it as long as the condition is true.

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

for loop statement

A

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:

  1. 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.
  2. 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.)
  3. The statement executes. To execute multiple statements, use a block statement ({ }) to group those statements.
  4. If present, the update expression afterthought is executed.
  5. Control returns to Step 2.

Example:

for (let i = 0; i < 5; i++) {
    console.log(i);
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

while loop statement

A

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;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

do...while loop statement

A

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);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is a labeled statement?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

break statement

A

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;
    }
  }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

continue statement

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

for...in loop statement

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How can you loop over the own properties of an object using the for...in statement?

A

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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

for...of loop statement

A

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).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly