Useful JavaScript Loops and Iteration

Loops offer a quick and easy way to do something repeatedly. This chapter of the JavaScript Guide introduces the different iteration statements available to JavaScript.

You can think of a loop as a computerized version of the game where you tell someone to take X steps in one direction, then Y steps in another.

There are many different kinds of loops, but they all essentially do the same thing: they repeat an action some number of times. (Note that it's possible that number could be zero!)

1. for statement

A for loop repeats until a specified condition evaluates to false. The JavaScript for loop is similar to the Java and C for loop.

A for statement looks as follows:
for ([initialExpression]; [conditionExpression]; [increment Expression]) statement

Example
<script>

function howMany (selectObject) {

let numberSelected = 0;

for (let i = 0 ; i < selectObject.options.length; i++) { if (selectObject.options[i].selected) { numberSelected++;

}

}

return numberSelected;

}

let btn = document.getElementById('btn');

btn.addEventListener('click', function() {

alert('Number of options selected: + howMany (document.selectForm.musicTypes));

});

</script>

2. do...while statement

The do...while statement repeats until a specified condition evaluates to false.

statement is always executed once before the condition is checked. (To execute multiple statements, use a block statement ({...}) to group those statements.) If condition is true, the statement executes again. At the end of every execution, the condition is checked. When the condition is false, execution stops, and control passes to the statement following do...while.
"
do

statement

while (condition); 
"
Example

let i = 0 ;

do {

i += 1;

console.log(i);

} while (i < 5) ;


3. while statement

A while statement executes its statements as long as a specified condition evaluates to true. A while statement looks as follows:

If the *condition *becomes false, statement within the loop stops executing and control passes to the statement following the loop.

The condition test occurs before statement in the loop is executed. If the condition returns true, statement is executed and the condition is tested again. If the condition returns false, execution stops, and control is passed to the statement following while.

"while (condition) statement"

Example

let n = 0 ;

let x = 0 ;

while (n < 3) {

n++;

X += n;

}


Comments

Popular Posts