Loops are control structures that execute other statements repetitively.
while
The while loop repeats the execution of the statement as long as expression evaluates to true. It has the following syntax:
while (expression) statement;
Before statement in the loop is executed, program tests the value of expression. If the value is false, then the program skips over the statement. Otherwise statement is executed and the value of expression is tested again. It is repeated while the expression is true.
Usually in the while loop there are executed multiple statements through using block statement (statements enclosed in {}).
An example:
var counter = 0; while (counter <= 5) { console.log(counter); counter++; }
The loop is repeated as long as the expression is evaluated to false. Most often it happens when a variable that is involved in expression changes in loop. In the example above if the counter was not increased, the loop would be infinite.
do-while
The do-while loop is similar to the while loop. The main difference is that first the statement is executed and then expression is checked.
do { statement; } while (expression);
It means that statement is always executed at least once.
An example:
var counter = 5; do { console.log(counter); // 5 is logged } while (counter <= 5);
Note that do-while loop must be terminated with a semicolon.
for
The for loop repeats as long as the condition is met. The syntax is as follows:
for (initialExpression; condition; incrementExpression) statement;
First initial expression is executed. Usually a counter variable is initialized here. Then before each iteration the condition is tested. If the value of condition is true statement in the body of the loop is executed. Finally the counter is updated, most frequently incremented.
An example:
for (var i = 0; i <= 3; i++) { console.log(i); } // Output: // 0 // 1 // 2 // 3
for-in
The for-in loop iterates over all the enumerable properties of an object. In each iteration the name of the property is stored in the variable. Here is the syntax:
for (variable in object) statement;
An example
var obj = {x: 5, y: 'abc', z: true}; for (var prop in obj) { console.log(prop + " = " + obj[prop]); }
It iterates over all the properties of the object and writes properties names and their values.
for-of
The for-of is a new loop introduced in ECMAScript 2015. It iterates over iterable objects (arrays, maps, sets and others). The syntax is as follow:
for (variable of object) statement;
In relation to the for-in loop, the for-of loop is a more convenient and iterates over property values:
var elements = ['a', 'b', 5, 6]; for (var element of elements) { console.log(element); } //Output: //a //b //5 //6
Reply