Thursday, November 10, 2016

JS loop and switch statement

Switch Statement

  • The switch statement is used to perform different actions based on a variety of different conditions, to select one of many blocks of code to be executed.
  • The way the switch statement works is separated into three parts, first the expression is evaluated, then the value of the expression is compared to the other values and lastly if the computer detects a match then that block gets executed.
  • The break keyword breaks out of the switch block. It will stop the execution of more code and case testing inside the block. This will appear once the match is found, and the job is done.
  • The default keyword  is responsible of specifying the code to run if there is no case match.



Loop Statement:
  • Loops are handy whenever you want to run the same code over and over again, with each time executing a different value. Loops can execute a block of code a number of times.
  • There are four different kinds of loops. The for loop, the for/in loop, the while loop and the do/while loop.
  • The for loop is often the tool you will use when you want to create a loop. 

            Syntax is
                  for (statement 1; statement 2; statement3)}
                            code block to be executed
                  }
       *Where as statement 1 is executed before the loop starts, statement 2 defines the condition for       running the loop and statement 3 is executed each time after the loop has been executed.
  • The for/in loop are loops through the properties of an object.
  • The while loop can execute a block of code as long as a specified condition is true.

            Syntax is
                  while(condition) {
                             code block to be executed
                   }
  • The do/while loop is a variant of the while loop. It will execute the code of block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.
            Syntax is
                 do{
                         code block to be executed
                     }
                 while (condition);




No comments:

Post a Comment