Most of the programming languages have a common set of programming constructs. JavaScript also provides a complete range of basic programming constructs.
JavaScript Conditional Statements
As in any other programming language conditional statements in JavaScript are used to perform different actions based on different conditions. While writing a code you may want to perform different actions for different decisions. For this JavaScript has following conditional statements:
1. If statement - use this statement if you want to execute some code only if a specified condition is true.
Syntax
if (condition)
{
/* code to be executed if condition is true*/
}
E.g. Using if statement
E.g.
Note: in case If is written in lowercase letters using uppercase letters (IF) will generate a JavaScript error!
2. if...else statement:- This statement is used if you want to execute some code if the condition is true and any another code if the condition is false.
Syntax:
if (condition)
{
// code executed if condition is true
}
else
{
// code executed if condition is not true
}
E.g. Displaying Greeting using if else construct
3. if...else if....else statement - use this statement if you want to select one of many blocks of code to be executed.
Syntax:
if (condition1)
{
//code to be executed if condition1 is true
}
else if (condition2)
{
//code to be executed if condition2 is true
}
else
{
//code to be executed if condition1 and condition2 are not true
}
E.g. if...else if....else statement
Note: While comparing variables you must always use two equals signs next to each other (==)!. In such case code executed only if the specified condition is true.
5. Switch statement – You can use Switch statement to select one of many blocks of code that is to be executed. With the Switch statement you can select from a number of alternatives.
Syntax:
switch(value)
{
Case 1:
//This code executed if first alternative is chosed
break;
Case 2;
//This code executed if second alternative is chosed
break;
default://used to take a default action
}
Note: You need to use break to come out of the Switch statement once selected case code is executed
Comments