if else / switch Statement
if Statement

if statement is use to check condition if condition is true then body of your code to be  execute.

Syntax:-
if (condition)
{
body of your code;
}

Example 1:-

<html>
<head>
<title>My JavaScript Programme</title>
</head>
<body>
<script language=\"javascript\">
var num=4;
if(num>0)
document.write(\"Positive\");
</script>
</body>
</html>

Output :-
Positve

if...else Statement.

In this case if statement is use to check condition, if condition is true then body of if block executed otherwise else block will be executed.

Syntax:-
if (condition)
{
body of your code;
}
else
{
body of your code;
}

Note curly braces({ }) is not required when if and else block  has single statement.

Example 2:- To find greater number between two number
<html>
<head>
<title>My JavaScript Programme</title>
</head>
<body>
<script language=\"javascript\">
var num1=4;
var num2=6;
if(num1>num2)
document.write(\"<b>First Number is greater</b>\");
else
document.write(\"<b>Second Number is greater</b>\");
</script>
</body>
</html>

Output :-
Second Number is greater
else if Statement.

if you have one more condition then use elseif statement.

Syntax:-
if (condition)
{
body of your code;
}
elseif (condition)
{
body of your code;
}
else
{
body of your code;
}

Example 1:- Find greater number amoung three number

<html>
<head>
<title>My JavaScript Programme</title>
</head>
<body>
<script language=\"javascript\">
var num1=14;
var num2=6;
var num3=23;
if(num1>num2 && num1>num3)
document.write(\"<b>First Number is greater</b>\");
else if(num2>num1 && num1>num3)
document.write(\"<b>Second Number is greater</b>\");
else
document.write(\"<b>Third Number is greater</b>\");
</script>
</body>
</html>

Output:-
Third Number is greater.

Switch Statement

Switch is basically use to make menu driven programme.In switch there many block but we select any one block depend upon user choice.

Syntax:-
switch (variable)
{
case label1:
code;
break;
case label2:
code;
case label3:
code;
break;
default:
code to be executed if n is different from both label1 and label2;
}

Example 4:- Simple code to use of switch statement

<html>
<head>
<title>My JavaScript Programme</title>
</head>
<body>
<script language=\"javascript\">
var num=2;
switch(num)
{
case 1:
document.write(\"First Number\");
break;
case 2:
document.write(\"Second Number\");
break;
case 3:
document.write(\"Third Number\");
break;
default:
document.write(\"Wrong Choice\");
}
</script>
</body>
</html>

Output:-
Second Number


Previous
Next