Loops & iterations in JavaScript

Loop executes the same code of block again and again. Loop is a control flow statement for specifying iteration, which allows code to be executed repeatedly. Repetitive task within a program to save time and effort.

Loops & Iterations in JavaScript

LABELLED STATEMENT

A label provides a statement with an identifier that lets you refer to it elsewhere in your program.

* * *

label:

statement

* * *

markLoop:

while (theMark) {

doSomething( );

}

BREAK & CONTINUE STATEMENT

A break statement can be used to terminate a loop, switch, or in conjunction with a labeled statement.

* * *

break;

break [label] ;

The continue statement can be used to restart a while, do-while, for, or label statement.

* * *

continue [label];

FOR… IN STATEMENT

The for…in statement iterates a specified variable over all the enumerable properties of an object.

For each distinct property, JavaScript executes the specified statements.

* * *

for (variable in object)

statement

* * *

function howMany (obj) {

tet numberselected0;

for (let i in obj) {

if (obj[i].selected) {

numberselected++;

}

}

return numberSelected;

}

FOR…OF STATEMENT

The for…of statement creates a loop iterating over iterable objects, invoking a custom iteration hook with statements to be executed for the value of each distinct property.

* * *

for (variable of object)

statement

* * *

const arr = [3, 5, 7];

arr.foo= ‘hello’;

for (let i in arr) {

console.log(i); / / logs “0, “1”, “2” “foo”

}

for (let i of arr) {

console. log(i); // logs 3, 5, 7

}

BREAK STATEMENT

The optional break statement ensures that the program breaks out of switch once the matched statement is executed.

Then continues execution at the statement following the switch.

If break is omitted, the program continues execution inside the switch statement (and will evaluate the next case, and so on).

Leave a Reply

Your email address will not be published. Required fields are marked *