JS Fundamentals - while Flashcards
example
let i = 3; while (i) { // when i becomes 0, the condition becomes falsy, and the loop stops alert( i ); i--; }
Inline variable declaration
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
Skipping parts
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
}
We can also remove the step part
We can also remove the step part:
let i = 0;
for (; i < 3;) {
alert( i++ );
}
We can actually remove everything, creating an infinite loop:
for (;;) { // repeats without limits }
when do we need break
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.
continue
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).
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.
(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
we can use break and continue with labels
to break a particular loop or continue with the next iteration of a particular loop
labels can not be used to jump anywhere
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.