JavaScript If-Else Statements

Updated on 29 Feb 2012,
Published on 10 Mar 2008

In JavaScript if-else statements are also known as conditional statements. If-else statements are used to execute any block of code conditionally e.g. if you want to execute any code only if condition satisfies that the input entered by the user is less than 5. At this point you can use if condition.

JavaScript Basics Examples:

You can see the live samples and examples of JavaScript Basics from the following links:

There are 3 types of if conditions:

1. if statement

2. if-else statement

3. if-else…if-else statement

1. if statement:

If you have a code that you want to execute only when the condition in if statement is true and there is no other code to be executed if the condition is false.

2. if-else statement:

If you have 2 pieces of code from which first part of the code will be executed when if condition is true and the other one will be executed when if condition is false.

3. if…else-if…else statements:

If you have number of conditions and for every condition you have another trapping if condition satisfying if condition, if…else-if…else statements can be used.

Example: if statement
var x=10;
var y=20;
   
if(x<y)
{
    alert('y is greater than x.');
}
Example: if-else statement
var x=10;
var y=5;
   
if(x<y)
{
    alert('y is greater than x.');
}
else
{
    alert('x is greater than y.');
}
Example: if...else-if...else statements
var x=10;
var y=10;
    
if(x<y)
{
    alert('y is greater than x.');
}
else if(x>y)
{
    alert('x is greater than y.');
}
else
{
    alert('x=y');
}

Output:

You can see the output of above discussed codes from the following links:

JavaScript If Condition

JavaScript If-Else Condition

JavaScript If-Else-If Conditions

If you have number of conditions then there is other option in JavaScript for conditional code execution.

Continue to next tutorial: JavaScript Switch Case statement to learn how to use variable based javascript switch conditional ladder.

0 Responses to "JavaScript If-Else Statements"
Leave a Comment
* required
* required
* will not be published
* optional
* hint: http://www.example.com
  • Subscribe via Email
  • HIRE EzineASP.Net Developers