Conditions Statements

Branching (Conditional) Statements


Branching With If Statements

An if statement is used to execute a statement or a block of statements on based of logical expression (condition). There are three different forms :

  • if … statement (simple if statement).
  • if … else statement.
  • If .. else if .. else statement (else if ladder statement)

if … statement

The ‘if’ is the simplest decision making statement. This statement is used to execute statement(s) only if a specified condition is true.

The Syntax is

if ( condition )
{
.. statement(s) to be executed if (condition) is true…
}

Example : A JavaScript program that displays ‘Good Morning India!’ if and only if time is less than 12 hours on web page otherwise page will remain blank.

<HTML>
<HEAD>
<TITLE>if statement</TITLE>
</HEAD>
<BODY>
<script type = “text/javascript”>
var d = new Date();
var time = d.getHours(); // time stores hours
if (time < 12)
{
document.write(“Good Morning India!”);
}
</script>
</BODY>
</HTML>

This HTML document displays the message “Good Morning India!” if your system time is less then 12 Hrs. Other wise you will find the page blank.


if … else … statement

This statement is an extension of the simple if statement. It permits one of two statement or group of statements depending upon the logical test.

The Syntax is

if ( condition )
{
True statement(s)…
}
else
{
False statement(s)…
}

If the logical expression (condition) is true, the true statement(s) will be executed. Otherwise, the false statement(s) will be executed.

Example : A JavaScript program that displays ‘Good Morning India!’ if time is less than 12 hours otherwise it shows ‘Good Day India!’ on the document.

<HTML>
<HEAD>
<TITLE>if else statement</TITLE>
</HEAD>
<BODY>
<script type = “text/JavaScript”>
var d = new Date();
var time = d.getHours();
if (time < 12)
{
document.write(“Good Morning India!”);
}
else
{
document.write(“Good Day India!”);
}
</SCRIPT>
</BODY>
</HTML>

This HTML document displays the message “Good Morning India!” if the system time is less then 12 hours. Other wise it display the message “Good Day India!”.


If...else if...else Statement

The if....else if...else statement is further an extension of the if… else… statement. This statement is useful for selecting one of many sets of statements to execute.

The Syntax is

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 any of the conditions is not true
}

Example : Write a program to check whether a number input through prompt box is Zero, Odd or Even.

<HTML>
<HEAD>
<TITLE>Odd, Even or Zero</TITLE>
</HEAD>
<BODY>
<SCRIPT type = “text/JavaScript”>
var n = prompt(“Enter your number:”,”Type your number here”);
n = parseInt(n); //converts string into number
if (n == 0)
alert(“The number is zero!”);
else if (n%2)
alert(“The number is odd!”);
else
alert(“The number is even!”);
</SCRIPT>
</BODY>
</HTML>

Selection with switch statement

A switch statement is used to execute different statement based on different conditions. It provides a better alternative than a long series of if… else if … statements.

The Syntax is

switch (expression)
{
case label1 : //executes when value
of exp. evaluates to label
statements;
break;
case label2 :
statements;
break;
...
default : statements; //executes when non of the above labels
//matches the result of expression
}

Example:

To compute the day of week (in words) while you input the date within prompt dialog box.

<HTML>
<HEAD>
<TITLE>Switch statement</TITLE>
</HEAD>
<BODY>
<script type=”text/JavaScript”>
// Enter date of birth to know the day of week on that day.
var d=new Date(prompt(“Enter your Date of Birth (e.g. November 17, 2002)”, “Month DD, YYYY”))
dy=d.getDay()
switch (dy)
{
case 0:
document.write(“It was <b>Sunday</b> on that day.”)
break
case 1:
document.write(“It was <b>Monday</b> on that day.”)
break
case 2:
document.write(“It was <b>Tuesday</b> on that day.”)
break
case 3:
document.write(“It was <b>Wednesday</b> on that day.”)
break
case 4:
document.write(“It was <b>Thursday</b> on that day.”)
break
case 5:
document.write(“It was <b>Friday</b> on that day.”)
break
case 6:
document.write(“It was <b>Saturday</b> on that day.”)
break
default:
document.write(“Please input a valid Date in? prescribed format !!!”)
}
</script>
</BODY>
</HTML>

LOOP STATEMENTS

Loop statements are the primary mechanism for telling a JavaScript interpreter to execute statements again and again until a specified condition is met. JavaScript supports following looping statements :

• for

• do … while

• while loop

Most loops have a counter variable which is initialised before the loop starts and then it is tested as part of the condition (expression) evaluated before every iteration of the loop. Finally, the counter variable is incremented or updated at the end of the loop body just before the condition is evaluated again.

For

The for loop consists of three optional expressions separated by semicolon, followed by a block of statements executed in the loop. Loop statements executed repeatedly again and again until the condition is false. The for loop is used when we know in advance how many times the script code should run.

The Syntax is

for([initial-expression]; [condition]; [increment-expression])
{
statements
}


Parameters

Initial-expression – used to initialise a counter variable.

Condition – If condition evaluates to true, the statements are executed.

Incr.-expression – to increment the counter variable.

Examples

The following for statement declares variable i and initialising it to 1. It checks that i is less than 20, performs the two succeeding statements, and increments i by 2 after each pass through the loop.

// for loop to display odd numbers between 1 to 20

for (var i = 1; i < 20; i+=2)
{
document.write(i);
document.write(“<BR>”);
}

Example:

A JavaScript program to generate the table of number 7 using for loop statement.

<HTML>
<HEAD>
<TITLE> Table of 7 </title>
</HEAD>
<BODY>
<SCRIPT language=”JavaScript” type=”text/JavaScript”>
document.write(“<H2> Table of number 7 </H2>”);
for(i = 1; i <= 10; i++ )

document.write(7*i);
document.write(“<BR>”);
}
</SCRIPT>
</BODY>
</HTML>

While

The while loop statement is simpler than the for loop. It consists of a condition and block statement. The condition is evaluated before each pass through the loop. If the condition is true then it executes block statement.

The Syntax is

while (condition)
{
statements
}

Example : The following while loop gives same output as for loop in previous example.

// While loop to display Odd numbers between 1 to 20
var i = 1; // Initialization of counter variable
while (i < 20) // Condition
{
document.write(i);
document.write(“<BR>”);
i++; // Updation
}

In while loop, we have to maintain a counter variable which controls the execution of statements in the loop.

Example:

Write a JavaScript program to generate first 10 Fibonacci numbers.

<HTML>
<HEAD>
<TITLE>Fibonacci Series</TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE=”JavaScript” TYPE=”text/JavaScript”>
// Program to print the Fibonacci series upto 10 numbers
document.write(“Fibonacci Series... upto 10 numbers <BR>”.fontsize(4));
//.fontsize to increase the font size of the string
i=0;
document.write(i + “ “);
j=1;
document.writeln(j + “ “);
var x = 3;
while (x <= 10)
{
t = i + j;
document.write(t + “ “);
i = j;
j = t;
x++;
}
</SCRIPT>
</BODY>
</HTML>

Do...While

The do...while loop is much like a while loop. It will repeat the loop until the specified condition is false. This loop will always be executed at least once, even if the condition is false, because the block of statements is executed before the condition is tested. In this loop statement, curly braces are optional.

The Syntax is

do
{
statements
}
while (condition);

Example: 

The following do…while loop gives same output as while loop in previous example.

// do…while loop to display Odd numbers between 1 to 20
var i = 1; // Initialization of counter variable
do
{
document.write(i);
document.write(“<BR>”);
i++; // Updation
}
while (i < 20); // Condition

Condition lies between the parentheses after the block of statements with while keyword.



Example Programs



Program [1]

Write a JavaScript that calculates the squares and cubes of the numbers from 0 to 10 and outputs HTML text that displays the resulting values in an HTML table format. 



View Solution

CCC Online Test 2021 CCC Practice Test Hindi Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) O Level NIELIT Study material and Quiz Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Website development Company in Allahabad Sarkari Exam Quiz