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 <span style="color:#cf2e2e" class="tadv-color">cond.js</span>
and then create an HTML page called <span style="color:#cf2e2e" class="tadv-color">ex06.html</span>
<span style="color:#cf2e2e" class="tadv-color">.</span>
Keep both in the same directory called <span style="color:#cf2e2e" class="tadv-color">Exercise 06.</span>
Conditional Statements in a JavaScript File
You need to create an external JavaScript file called <span style="color:#cf2e2e" class="tadv-color">cond.js</span>
in a directory called <span style="color:#cf2e2e" class="tadv-color">Exercise 06</span>
.
The steps to create the JavaScript with conditional statements is given below.
Step 1: Open a new notepad and save it as <span style="color:#cf2e2e" class="tadv-color">cond.txt.</span>
Step 2: Open the <span style="color:#cf2e2e" class="tadv-color">cond.txt</span>
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 <span style="color:#cf2e2e" class="tadv-color">cond.js</span>
and close the file.
HTML Page
Now, you will create a new HTML page called <span style="color:#cf2e2e" class="tadv-color">ex06.html</span>
and link the <span style="color:#cf2e2e" class="tadv-color">cond.js</span>
<span style="color:#cf2e2e" class="tadv-color"> </span>
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
.
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 <span style="color:#cf2e2e" class="tadv-color">ex06.html</span>
and close it.
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
.