JavaScript For Loop

Loops are great way by which same piece of code could be reiterated. Usage of loop statements helps in making the complete code more compact and used mostly in the array.

Types of Loops

There can be four main types of loops available in JavaScript.

  • for loop
  • while loop
  • do-while loop
  • for-in loop

Simple way to understand JavaScript Loops

Loops could come in handy for any programmer as he could avoid repeating the same form of code again and again. For example consider below lines. Now instead of writing below.

switch(expression) {     //this is the expression which is to be checked
    case n:
        code block
    case n:
        code block
        default code block // this is the value of the code which is to be executed if no match found


switch (new Date().getDay()) {
    case 0:
        day = "Sunday";
    case 1:
        day = "Monday";
    case 2:
        day = "Tuesday";
    case 3:
        day = "Wednesday";
    case 4:
        day = "Thursday";
    case 5:
        day = "Friday";
    case 6:
        day = "Saturday";

How Switch Statement works

It can be used to check one type of expression or condition. The values for each case are compared based on the output of that expression. If match is found, then that particular line of code is executed based on the value and expression tested. Only the associated block of code is executed. There could be single or even multiple expressions tested in JavaScript switch statement and can be used with characters, numbers etc. One can use different type of expressions or cases which need to be tested and based on that code could be executed. It is very useful when there are various possibilities in the code.

Use of Break keyword in Switch

In the above example, you could see break statement is used. It is a useful way to terminate the switch statement when the line of codes or required expression is executed. If break statement is not used, then it could cause an endless loop. Every case under switch statement is terminated with break statement.