Javascript if else


If flow control statements allow execution of code fragments according to conditions. If flow control is divided into three categories:

  1. if
  2. if...else
  3. if...else if...else

The if statement

if (expr) {
    statement
}

This syntax means that if the expr expression holds, the code within {statement} is executed.

example :

var x = 3;
var y = 1;
if (x > y)
   alert("x greater than y");

if ... else

if (expr) {
    statement1
} else {
    statement2
}

This syntax indicates that statement1 is executed as long as expr holds, otherwise statement2 is executed.

example:

var x = 1;
var y = 3;
if (x>y)
    alert("x greater than y");
} else {
    alert("x less than  equal y");
}

Run the example, will pop-up prompt box and prompt text: x less than or equal to y.


if ... else if ... else

if (expr1) {
    statement1
} else if (expr2) {
    statement2
} else {
    statement3
}

This syntax indicates that statement1 is executed as long as expr1 is met, else expr2 is detected; statement2 is executed if expr2 holds; statement3 is executed if expr2 is not true.

var x = 3;
var y = 3;
if (x>y) {
    alert("x greater than y");
} else if (x < y) {
    alert("x less than y");
} else {
    alert("x equal y");
}

Run the example, will pop-up prompt box and prompt text: x is equal to y.

Note

else if there can be more than one, in order to achieve more selection criteria, but in most cases, more conditions, we can choose JavaScript switch to achieve.




Copyright 2014-2017 by DeveloperTut.com. All Rights Reserved.
TwitterGoogle+Facebook