JavaScript IF ELSE

JavaScript If Else condition evaluates the expression, If expression is true, execute the true block otherwise execute else block.

JavaScript Conditional Statements,

  1. If Statement
  2. If Else Statement
  3. If Else If Statement

JavaScript Example,

  1. If statement with Logical Operators

Note:
Curly brackets are used to define the block of the code. It's optional when write single statement.
And when writing multiple statements used curly braces {} for identifying group statements.

JavaScript If Statement

If statement evaluates the expression, and if the condition becomes true execute the if block otherwise skip and execute the next statements.

Syntax

if ( condition ) { 
    // Do stuff if condition is true 
}
if ( true ){
    // Do stuff if condition is true 
}

Example

var a = 5;
if (a) {    // variable a = 5 value, so expression of 'a' return true
    document.write("Value of a:" + a);
}

Run it...   »

JavaScript If Else Statement

If...Else statement checking two different possibility. If the condition becomes true, execute block of code otherwise executes else block.

Syntax

if ( condition ) { 
    // Do stuff if is true 
} else { 
    // Do stuff if is not true
}

Example

var a = 5, b= 10;
if (a > b) {
    document.write("a is bigger than b");
} else {
    document.write("a is smaller than b");
}

Run it...   »

JavaScript If Else IF Statement

JavaScript else if statement evaluates the if condition and execute a block of code if expression become true, otherwise check the next else if condition and so on.

If specified if else condition not satisfied then execute the else block of code.

Syntax

if ( condition1 ) { 
    // Do stuff if condition is true 
} else if ( Condition2 ) { 
    // Do stuff if Condition2 is true 
} else if ( Condition3 ) { 
    // Do stuff if Condition3 is true 
} else { 
    // Do stuff if not above condition is not true
}

Example

var a = 10, b= 10;
if (a > b) {
    document.write("a is bigger than b");
} else if (a == b) {
    document.write("a is equal to b");
} else {
    document.write("a is smaller than b");
}

Run it...   »

JavaScript If statement with Logical Operators

Logical AND (&&) - If condition evaluates and return true whether all condition satisfied, otherwise return false.

Example

var a = 10, b = 5;
if (a && b && a > b)        // true && true && true
    document.write("a is bigger than b");
else
    document.write("a is smaller than b");

Run it...   »


Logical OR (||) - If condition evaluates and return true at least one condition true, otherwise return false.

Example

var a, b;
if (a || b)         // false || false
    document.write("a and b both are defined.");
else
    document.write("a and b undefined.");

Run it...   »


Logical NOT (!) - If condition evaluates the inverse of the given value result true become false, and false become true.

Example

var a;
if (!a)         // true
    document.write("a is undefined.");

Run it...   »