JS Fundamentals - while Flashcards

1
Q

example

A
let i = 3;
while (i) { // when i becomes 0, the condition becomes falsy, and the loop stops
  alert( i );
  i--;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Inline variable declaration

A

Here, the “counter” variable i is declared right in the loop. This is called an “inline” variable declaration. Such variables are visible only inside the loop.

for (let i = 0; i < 3; i++) {
  alert(i); // 0, 1, 2
}
alert(i); // error, no such variable
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Skipping parts

A

Any part of for can be skipped.

For example, we can omit begin if we don’t need to do anything at the loop start.

let i = 0; // we have i already declared and assigned

for (; i < 3; i++) { // no need for “begin”
alert( i ); // 0, 1, 2
}

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

We can also remove the step part

A

We can also remove the step part:

let i = 0;

for (; i < 3;) {
alert( i++ );
}

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

We can actually remove everything, creating an infinite loop:

A
for (;;) {
  // repeats without limits
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

when do we need break

A

The combination “infinite loop + break as needed” is great for situations when a loop’s condition must be checked not in the beginning or end of the loop, but in the middle or even in several places of its body.

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

continue

A

The continue directive is a “lighter version” of break. It doesn’t stop the whole loop. Instead, it stops the current iteration and forces the loop to start a new one (if the condition allows).

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

No break/continue to the right side of ‘?’
Please note that syntax constructs that are not expressions cannot be used with the ternary operator ?. In particular, directives such as break/continue aren’t allowed there.

A

(i > 5) ? alert(i) : continue; // continue isn’t allowed here
…it stops working: there’s a syntax error.

This is just another reason not to use the question mark operator ? instead of if

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

we can use break and continue with labels

A

to break a particular loop or continue with the next iteration of a particular loop

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

labels can not be used to jump anywhere

A

Labels do not allow us to jump into an arbitrary place in the code.

For example, it is impossible to do this:

break label; // doesn’t jumps to the label below

label: for (…)
A call to break/continue is only possible from inside a loop and the label must be somewhere above the directive.

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