Block nesting

Block nesting means that you put one block structure inside another block structure. It can be an if block inside another if block after the comparison or an else block inside another else block.

Example:


var HondaShop = "yes";
var HondaPCX = "yes";
  if (HondaShop == "yes") {
     if (HondaPCX == "yes") {
          window.alert ("Motorbike found");
     }
     else {
          window.alert ("Have a shop but no motorbike");
     }
  }
  else {
     window.alert ("You need to find a Honda shop");
  }

The code starts with two declared variables, both with the value of yes. Then we have an if block and an else block. Within the if block (after the comparison) an entire if/else structure is nested.

You can also nest another if/else statement within the else block of your script. Notice a new variable called WebAccess that is used in the nested if/else statement nested within the else block of the script.


var HondaShop = "yes";
var HondaPCX = "yes";
var WebAccess = "yes";
  if (HondaShop == "yes") {
     if (HondaPCX == "yes") {
          window.alert ("Motorbike found");
     }
     else {
          window.alert ("Have a shop but no motorbike");
} } else { if (WebAccess == "yes") { window.alert ("Find a Honda shop online");
} else { window.alert ("You need to find a Honda shop"); } }

You can nest as many blocks as you want within other blocks. You can have for example an if/else statement nested within an if block which is also nested within another if block.

Leave a Reply