CONTROL STRUCTURES IN JAVASCRIPT

CONTROL STRUCTURES:

The control structures within JavaScript allow the program flow to change within a unit of code or function. These statements can determine whether or not given statements are executed, as well as repeated execution of a block of code.
There are three ways to change the control structures of a program by using:
1.conditional statements-( IF..THEN, . SWITCH)
2. looping control-(.FOR, WHILE, DO..WHILE)
3.branch logic-(FUNCTIONS AND PROCEDURES)

IF …THEN:

Sytanx: if (test condition ) {
              Statements to be executed if the test condition is true
}

Description:The if statement is straight forward - if the given expression is true, the statement or statements will be executed. Otherwise, they are skipped.

Example:

if (a === b) {

  document.body.innerHTML += "a equals b";
}


IF..THEN…ELSE:

Syntax:
If (test condition_1){

          Statements to be executed if test condition_1 is true

         }else if(test condition_2){

Statements to be executed if test condition_2 is true

}else{

Statements to be executed if test condition_2 is false
}

Description: The if statement may also consist of multiple parts, incorporating else and else if sections. These keywords are part of the if statement, and identify the code blocks that are executed if the preceding condition is false.

Example:

if (a === b) {
  document.body.innerHTML += "a equals b";
} else if (a === c) {
  document.body.innerHTML += "a equals c";
} else {
  document.body.innerHTML += "a does not equal either b or c";
}

SWITCH:

Syntax:

switch(i) {

case 1:
  // ...
  break;
case 2:
  // ...
  break;
default:
  // ...
  break;
}

Description:

  • The switch statement evaluates an expression, and determines flow control based on the result of the expression:
  • When i gets evaluated, it's value is checked against each of the case labels. These case labels appear in the switch statement and, if the value for the case matches i, continues the execution at that point. If none of the case labels match, execution continues at the default label (or skips the switch statement entirely if none is present.)
  • Case labels may only have constants as part of their condition.
  • The break keyword exits the switch statement, and appears at the end of each case in order to prevent undesired code from executing.
  • The continue keyword does not apply to switch statements.

Example:

var trees = "green";

switch (trees) {
  case "purple":
    alert("Trees are purple");
    break;
  case "pink":
    alert("Trees are pink");
    break;
  case "green":
    alert("Trees are green");
    break;
  default:
    alert("Trees are an unknown colour");
}







No comments:

Post a Comment