News & UpdatesProgrammingWeb programming Store My Projects
Links
Affiliates

JavaScript Tutorial – 06 – Conditionals

JavaScript tutorials

The conditional statements execute different code blocks for different conditions.

If statement

The if statement will execute only if the condition inside the parenthesis is true.

if (x < 0.5) {     
  document.write(x + " < 0.5"); 
}

To test for other conditions any number of else if clauses can be added. For handling all other cases there can be one else clause at the end.

if (x < 0.5) {     
  document.write(x + " < 0.5"); 
}
else if (x > 0.5) {
  document.write(x + " > 0.5"); 
}
else {
  document.write(x + " == 0.5"); 
}

The curly brackets can be left out if only one statement needs to be executed conditionally.

if (x < 0.5)      document.write(x + " < 0.5"); 
else if (x > 0.5) document.write(x + " > 0.5"); 
else              document.write(x + " == 0.5");

Switch statement

The switch statement checks if a string or number is equal to a case label and then executes the matching case. It can contain any number of cases and it can end with a default label for handling all other cases.

switch (x) 
{
  case 0: document.write(x + " is 0"); break;
  case 1: document.write(x + " is 1"); break;
  default: document.write(x + " is something else");
}

Note that the statements after each case label are not surrounded by curly brackets. Instead, the break keyword is used to stop execution from continuing over to the next case.

Ternary operator

In addition to the if and switch statements there’s the ternary operator (?:) that can replace an if/else clause. This operator takes three expressions. If the first one is true the second expression is evaluated and returned, and if it’s false the third one is.

(x == 1) ? x = 0 : x = 1; // Ternary operator statement
x = (x == 1) ? 0 : 1;     // Ternary operator expression
Recommended additional reading:
Sams - Teach Yourself JavaScript in 24 Hours