A loop is a piece of code that repeats a certain number of times. The number of repetitions or the number of iterations is described with a counter.
The loop is written with while(an expression that is converted to a boolean type -> for the next iteration, you need to get true, as soon as we get false, the loop will stop);
An example of an infinite loop: while (true);
Which translates to false in JavaScript:
- false
undefined
null
0
” “
NaN
Everything else is true.
To set the counter, we introduce a variable:
var i = 0; // start counting from zero
And inside the code, add a change in the counter i<10 (so far less than 10) change the value of i to i+1 through the short notation i+=1.
To shorten the spelling i+=1, you can use the unary increment operators (++ increases the value of the operand by one) and decrement (– decreases the value of the operand by one). The ++/– operators can appear both before and after the operand (variable) and will be called post-increment/-decrement and pre-increment/-decrement respectively. Pre-operators = first change to one, and then use the operand (variable), and post-operators = first use the operand (variable), and then change to one.
The counter variable can be called any letters, but it is customary to call it i (iteration).
Loop example:
var i=0;
while (i<10) {console.log(i); i+=1;};
The curly braces are not directly related to the loop syntax, they indicate that what is inside the {…} must be executed at one time as a whole.
There is an even more complex for loop – read about it in the next article.