How to Write Conditional Statements in JavaScript?

The different types of conditional statements used in JavaScript for making different decisions are as follows.

If Statement

This statement is used to execute some code only if a specified condition is true.

Syntax:

if {condition}
{
code to be executed if condition is true
}

Example:

<script type=”text/javascript”>
var d=new Date()
var time=d.getHours()
if (time<10)
{
document.write(“<b>Good morning</b>”)
}
</script>
This script writes “Good morning” greeting if the time is less than 10

 

If …. elese statement

This statement is used to execute some code only if the condition is true and another code if the condition is false.

Syntax:

if {condition}
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}

Example:

<script type=”text/javascript”>
var d=new Date()
var time=d.getHours()
if (time<10)
{
document.write(“Good morning”)
}
else
{
document.write(“Good Day”)
}
</script>

Preview:

About shuseel

Shuseel Baral is a web programmer and the founder of InfoTechSite has over 5 years of experience in software development, internet, SEO, blogging and marketing digital products and services is passionate about exceeding your expectations.

Leave a Comment

Your email address will not be published. Required fields are marked *