About JavaScript Loops ▷ While, For, Do while, Switch

5/5 - (1 vote)

JavaScript loops are used to execute the same code multiple times.
They can execute a block of code as long as a specified condition is true.

The While Loop

The while loop executes a block of code as long as a specified condition is true.
The While loop has the following syntax:

while (condition) {
    code block to be executed
}

Display numbers from 1 to 10 using While loop

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Display numbers from 1 to 10 using While loop</title>
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20type%3D%22text%2FJavascript%22%3E%0Afunction%20myFunction()%7B%0A%09var%20num%20%3D%201%3B%0A%09var%20text%20%3D%20%22%22%3B%0A%09while%20(num%20%3C%3D%2010)%7B%0A%09text%20%2B%3D%20%22%3Cwp-br%2F%3E%22%20%2B%20num%3B%0A%09%20%20num%2B%2B%3B%0A%09%7D%0A%09document.getElementById(%22result%22).innerHTML%20%3D%20text%3B%0A%7D%0A%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;script&gt;" title="&lt;script&gt;" />
</head>
<body onload="myFunction()">
<p id="result">
</p>
</body>
</html>

Be careful!
To avoid infinite loops You must always increment the variable that is used in the condition of the loop (in the example above, the variable num).
Otherwise, the loop will never end, which will cause the browser to crash.

The Do/While Loop

The Do/While loop has the following syntax:

do {
code block to be executed
}
while (condition);

The difference between “while loop” and “do/while loop” is that the condition is set to end.

The Do/While block will always be executed, at least once, before checking the condition, and will repeat the loop as long as the condition is true.

Display numbers from 1 to 10 using Do/While loop

let num = 1;
do {
    console.log(num);
    num++;
} while (num <= 10);

Execution of do / while once even if the condition is false

let num = 5;
do {
    console.log("The number is high");
} while (num > 100);

//Result: The number is high

The For Loop

The For Loop is used to loops through a block of code a number of times.

The for loop has tree steps:

  • statement 1 = set the index;
  • statement 2 = then, check the condition;
  • and statement 3 = finally, increment the index;

The for loop has the following syntax:

for (statement 1; statement 2; statement3){
    code block to be executed
}

Statement 1 is optional, you can omit Statement 1, for example if You set values before the loop starts.

Statement 2 is also optional to.

If Statement 2 returns true, the loop will never end (will start over again), so you must provide a break instruction inside the loop, to stop it.

Break instruction will jump out of the loop.

Statement 3 is optional too, You can omit Statement 3 when You increment the index inside the loop.

The increment doesn’t have to go by 1, Statement 3 can be anything.

The code block

Regardless of what’s in your loop, it doesn’t matter. Whatever is in the code block between the braces, it will be executed!

Display numbers from 1 to 10 using For loop

for (var i = 1; i <= 10; i++) {
    console.log(i);
}

// 1,2,3,4,5,6,7,8,9,10

Break

The “break” statement is used to jump out of a loop.

The “break” jump completely out of the loop and continue to execute the code after the loop.

for (var i = 1; i <= 10; i++) {
    if (i == 5) {
        break;
    }
    console.log(i);
}

//Result: 1,2,3,4

Continue

The “continue” statement is similar with break, the difference is that “continue” does not jump completely out of the loop, it jump only the iteration where is found “continue”.

After that continue with the next iteration in the loop.

for (var num = 1; num < 10; num++){
		if (num == 5){
		continue;
	}
	console.log(num);
}


//Result: 1,2,3,4,6,7,8,9

Switch Statement

It is recommended to use a switch instead of multiple if…else statements.

The code will be simpler and clearer.

How Switch Statement will work?

  • The switch expression is evaluated once.
  • The value of the expression is compared with the values of each case.
  • If find a match, the associated block of code is executed.
  • If there is no match, the default code block is executed.
let num2 = 5;
switch (num2) {
    case 0:
        console.log("Number is 0");
        break;
    case 10:
        console.log("Number is 10");
        break;
    case 100:
        console.log("Number is 100");
        break;
    default:
        console.log("I don't know the number");
}

//I don't know the number

Read more here about JavaScrip Switch Statement, Multiple case statements, Strict comparison, Exercises, and examples

Javascript loop examples

Print Vowels and Consonants

First, print each vowel in s on a new line. The English vowels are a, e, i, o, and u, and each vowel must be printed in the same order as it appeared in.
Second, print each consonant (i.e., non-vowel) in s on a new line in the same order as it appeared in.

function vowelsAndConsonants(s) {
    let consonents = [];
    for (let l in s){
        if ("aeiou".includes(s[l])){
            console.log(s[l]);    
        }
        else {
            consonents.push(s[l]);
        }
    }
    for (let nV in consonents){
        console.log(consonents[nV]);
    }
}

Hello there!

I hope you find this post useful!

I'm Mihai, a programmer and online marketing specialist, very passionate about everything that means online marketing, focused on eCommerce.

If you have a collaboration proposal or need helps with your projects feel free to contact me. I will always be glad to help you!

subscribe youtube

Leave a Comment

WebPedia.net