Basic JavaScript – Exercise 06 -Conditional Statements

Advertisements
Advertisements

Conditional statements in JavaScript uses if-else or switch statement that change the direction of the program in run-time. The conditional statement check certain conditions and then based on the truth value of the condition, execute a block of code.

The if-else statements could be nested to make a if-if-else-else or if-else- else-if statements. The general structure of if-else statement is as follows

if (condition) 
{     
   statement 1... 
} 
else 
{     
   statement 2... 
}

In the above example, if the condition is true – statement 1 is executed, else – the statement 2 is executed. In this article, you will create a JavaScript file with conditional statement called cond.js and then create an HTML page called ex06.html. Keep both in the same directory called Exercise 06.

Conditional Statements in a JavaScript File

You need to create an external JavaScript file called cond.js in a directory called Exercise 06.

The steps to create the JavaScript with conditional statements is given below.

Advertisements

Step 1: Open a new notepad and save it as cond.txt.

Figure 1: Cond.txt
Figure 1: Cond.txt

Step 2: Open the cond.txt file and insert the following code.

var a = 10 
var b = 100 
var c = a + b 
if(c > 100) 
{ 
    document.write("a = 10" + ""); 
    document.write("b = 100"+ ""); 
    document.write("c= a + b"+ ""); 
    document.write(" " + "C is more than 100" + " "); 
} 
else 
{ 
    document.write("a = 10"+ ""); 
    document.write("b = 100"+ ""); 
    document.write("c= a + b"+ ""); 
    document.write( " " + "C is less than 100" + " "); 
}

Step 3: Save the file as cond.js and close the file.

Figure2-cond.js
Figure2-cond.js

HTML Page

Now, you will create a new HTML page called ex06.html and link the cond.js file to the HTML page. To create the HTML page follow the steps below.

Step 1: Open a note pad  and save it as ex06.txt.

Figure1-ex06
Figure1-ex06

Step 2: Open the ex06.txt file and insert the following code.

<html>
<head>
<title>
    Basic JavaScript - Exercise-06 - Conditional Statements 
</title>
    <script type="text/javascript" src="cond.js"></script>
</head>
<body>
    <p>Example of Conditional Statement </p>
</body>
</html>

Step 3: Save the ex06.txt file to ex06.html and close it.

Figure2-ex06 - Conditional statements in JavaScript
Figure2-ex06 – Conditional statements in JavaScript

Output

The program read have two variables A = 10, B = 100. There sum is C = A + B . If C is greater then 100 , following output is displayed on the screen, else a different output will be printed. All depends on the condition whether C > 100.

Output - Conditional statements in JavaScript
Output – Conditional statements in JavaScript
Advertisements
Advertisements
Advertisements