Note_Tech

All technological notes.


Project maintained by simonangel-fong Hosted on GitHub Pages — Theme by mattgraham

Javascript - Conditional Statement

Back


Conditional Statement

Situation to execute Statement
condition is true if
condition is false else
new condition else if
alternative conditiona switch

if Statement

if (condition) {
  //  block of code to be executed if the condition is true
}

else Statement

if (condition) {
  //  block of code to be executed if the condition is true
} else {
  //  block of code to be executed if the condition is false
}

else if Statement

if (condition1) {
  //  block of code to be executed if condition1 is true
} else if (condition2) {
  //  block of code to be executed if the condition1 is false and condition2 is true
} else {
  //  block of code to be executed if the condition1 is false and condition2 is false
}

switch Statement

switch (expression) {
  case value1:
    // code block
    break;
  case value2:
    // code block
    break;
  default:
  // code block
}

The break Keyword


The default Keyword

console.log("\n-------- switch --------\n");
switch (new Date().getDay()) {
  default:
    console.log("Weekday");
    break;
  case 6:
    console.log("Saturday");
    break;
  case 0:
    console.log("Sunday");
}

Shared Block

console.log("\n-------- switch --------\n");
switch (new Date().getDay()) {
  case 4:
  case 5:
    console.log("Soon it is Weekend");
    break;
  case 0:
  case 6:
    console.log("It is Weekend");
    break;
  default:
    console.log("Looking forward to the Weekend");
}

TOP