Wednesday, October 7, 2020

JavaScript Loops

Loops are used to execute the same block of code again and again, as long as a certain condition is met. The basic idea behind a loop is to automate the repetitive tasks within a program to save time and effort. JavaScript now supports five different types of loops:

  • while — loops through a block of code as long as the condition specified evaluates to true.
  • do…while — loops through a block of code once; then the condition is evaluated. If the condition is true, the statement is repeated as long as the specified condition is true.
  • for — loops through a block of code until the counter reaches a specified number.
  • for…in — loops through the properties of an object.
  • for…of — loops over iterable objects such as arrays, strings, etc.

In the following sections, we will discuss each of these loop statements in detail.

The while Loop

This is the simplest looping statement provided by JavaScript.

The while loop loops through a block of code as long as the specified condition evaluates to true. As soon as the condition fails, the loop is stopped. The generic syntax of the while loop is:

while(condition) {
    
// Code to be executed
}
 

The following example defines a loop that will continue to run as long as the variable i is less than or equal to 5. The variable i will increase by 1 each time the loop runs:

Example

var i = 1;

while(i <= 5) {   

    document.write("<p>The number is " + i + "</p>");

    i++;

}

Note: Make sure that the condition specified in your loop eventually goes false. Otherwise, the loop will never stop iterating which is known as infinite loop. A common mistake is to forget to increment the counter variable (variable i in our case). 


The do...while Loop

The do-while loop is a variant of the while loop, which evaluates the condition at the end of each loop iteration. With a do-while loop the block of code executed once, and then the condition is evaluated, if the condition is true, the statement is repeated as long as the specified condition evaluated to is true. The generic syntax of the do-while loop is:

do {
    // Code to be executed
}
while(condition);

The JavaScript code in the following example defines a loop that starts with i=1. It will then print the output and increase the value of variable i by 1. After that the condition is evaluated, and the loop will continue to run as long as the variable i is less than, or equal to 5.

Example

var i = 1;

do {

    document.write("<p>The number is " + i + "</p>");

    i++;

}

while(i <= 5);

Difference Between while and do...while Loop

The while loop differs from the do-while loop in one important way — with a while loop, the condition to be evaluated is tested at the beginning of each loop iteration, so if the a conditional expression evaluates to false, the loop will never be executed.

With a do-while loop, on the other hand, the loop will always be executed once even if the conditional expression evaluates to false, because unlike the while loop, the condition is evaluated at the end of the loop iteration rather than the beginning.

 

The for Loop

The for loop repeats a block of code as long as a certain condition is met. It is typically used to execute a block of code for a certain number of times. Its syntax is:

for(initializationconditionincrement) {
    
// Code to be executed
}

The parameters of the for loop statement have following meanings:

  • initialization — it is used to initialize the counter variables, and evaluated once unconditionally before the first execution of the body of the loop.
  • condition — it is evaluated at the beginning of each iteration. If it evaluates to true, the loop statements execute. If it evaluates to false, the execution of the loop ends.
  • increment — it updates the loop counter with a new value each time the loop runs.

The following example defines a loop that starts with i=1. The loop will continue until the value of variable i is less than or equal to 5. The variable i will increase by 1 each time the loop runs:

Example

for(var i=1; i<=5; i++) {

    document.write("<p>The number is " + i + "</p>");

}

The for loop is particularly useful for iterating over an array. The following example will show you how to print each item or element of the JavaScript array.

Example

// An array with some elements

var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"]; 

// Loop through all the elements in the array

for(var i=0; i<fruits.length; i++) {

    document.write("<p>" + fruits[i] + "</p>");

}


The for...in Loop

The for-in loop is a special type of a loop that iterates over the properties of an object, or the elements of an array. The generic syntax of the for-in loop is:

for(variable in object) {
    
// Code to be executed
}

The loop counter i.e. variable in the for-in loop is a string, not a number. It contains the name of current property or the index of the current array element.

The following example will show you how to loop through all properties of a JavaScript object.

Example

// An object with some properties

var person = {"name": "Clark", "surname": "Kent", "age": "36"}; 

// Loop through all the properties in the object 

for(var prop in person) { 

document.write("<p>" + prop + " = " + person[prop] + "</p>");

}

Similarly, you can loop through the elements of an array, like this:

Example

// An array with some elements

var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"]; 

// Loop through all the elements in the array

for(var i in fruits) { 

    document.write("<p>" + fruits[i] + "</p>");

}

Note: The for-in loop should not be used to iterate over an array where the index order is important. You should better use a for loop with a numeric index.

 

The for...of Loop Loop ES6

ES6 introduces a new for-of loop which allows us to iterate over arrays or other iterable objects (e.g. strings) very easily. Also, the code inside the loop is executed for each element of the iterable object.

The following example will show you how to loop through arrays and strings using this loop.

Example

// Iterating over array

let letters = ["a", "b", "c", "d", "e", "f"]; 

for(let letter of letters) {

    console.log(letter); // a,b,c,d,e,f

} 

// Iterating over string

let greet = "Hello World!"; 

for(let character of greet) {

    console.log(character); // H,e,l,l,o, ,W,o,r,l,d,!

}

 

Note: The for...of loop doesn't work with objects because they are not iterable. If you want to iterate over the properties of an object you can use the for-in loop.

 



JavaScript Switch

The switch..case statement is an alternative to the if...else if...else statement, which does almost the same thing. The switch...case statement tests a variable or expression against a series of values until it finds a match, and then executes the block of code corresponding to that match. It's syntax is:

switch(x){
    
case value1:
        // Code to be executed if x === value1
        break;
    
case value2:
        // Code to be executed if x === value2
        break;
    ...
    
default:
        // Code to be executed if x is different from all values
}

Consider the following example, which displays the name of the day of the week.

Example

var d = new Date()     

switch(d.getDay()) {

      case 0:

            alert("Today is Sunday.");

            break;

      case 1:

            alert("Today is Monday.");

            break;

      case 2:

            alert("Today is Tuesday.");

            break;

      case 3:

            alert("Today is Wednesday.");

            break;

      case 4:

            alert("Today is Thursday.");

            break;

      case 5:

            alert("Today is Friday.");

            break;

      case 6:

            alert("Today is Saturday.");

            break;  

      default:

            alert("No information available for that day.");

            break;

}

The getDay() method returns the weekday as a number from 0 and 6, where 0 represents Sunday.  

Note: In a switch...case statement, the value of the expression or variable is compared against the case value using the strict equality operator (===). That means if x = "0", it doesn't match case 0:, because their data types are not equal.

The switch...case statement differs from the if...else statement in one important way. The switch statement executes line by line (i.e. statement by statement) and once JavaScript finds a case clause that evaluates to true, it's not only executes the code corresponding to that case clause but also executes all the subsequent case clauses till the end of the switch block automatically.

To prevent this you must include a break statement after each case (as you can see in the above example). The break statement tells the JavaScript interpreter to break out of the switch...case statement block once it executes the code associated with the first true case.

The break statement is however not required for the case or default clause when it appears at last in a switch statement. Although, it a good programming practice to terminate the last case, or default clause in a switch statement with a break. It prevents a possible programming error later if another case statement is added to the switch statement.

The default clause is optional, which specify the actions to be performed if no case matches the switch expression. The default clause does not have to be the last clause to appear in a switch statement. Here's an example, where default is not the last clause.

Example

var d = new Date(); 

switch(d.getDay()) {

    default:

        alert("Looking forward to the weekend.");

        break;

    case 6:

        alert("Today is Saturday.");

        break;

    case 0:

        alert("Today is Sunday.");

}

 

Multiple Cases Sharing Same Action

Each case value must be unique within a switch statement. However, different cases don't need to have a unique action. Several cases can share the same action, as shown here:

Example

var d = new Date(); 

switch(d.getDay()) {

    case 1:

    case 2:

    case 3:

    case 4:

    case 5:

        alert("It is a weekday.");

        break;

    case 0:

    case 6:

        alert("It is a weekend day.");

        break;

    default:

        alert("Enjoy every day of your life.");

}