Conditional Statements in JavaScript

January 29, 2025 No Comments » Hits : 137






In JavaScript we have following conditional statements -

  1. if statement
  2. if…else statement
  3. if….else if…..else ladder
  4. switch statement

Why we need conditional statements ?

Conditional statements are used to perform certain action depending on the condition. Depending on the current situation we can decide code flow at run time.


if Statement

if(condition)
  {
  statement 1
  statement 2
  .
  .
  .
  statement 3
  statement 4
  }

Live Example :

<html>
<body>
<script type="text/javascript">
var d = new Date();
var time = d.getHours();
if (time < 10)
  {
  document.write("<b>Good morning</b>");
  }
</script>
</body>
</html>

Explanation :

  1. Check whether current time is less than 10 or not.
  2. If time is less than 10 then we are going to print “Good Morning” message.
  3. If block will never be executed if time is greater than 10.
  4. if statement is written in lowercase “if”. “IF” will generate JavaScript error.

if….else Statement

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

Live Example :

<html>
<body>
<script type="text/javascript">
var d = new Date();
var time = d.getHours();
if (time < 10)
  {
  document.write("<b>Good morning</b>");
  }
else
  {
  document.write("<b>Have a good day</b>");
  }
</script>
</body>
</html>

Explanation :

  1. if..else statement check condition inside if.
  2. If condition mentioned inside if statement is true then it will execute “if block“.
  3. If condition mentioned inside if statement is false then it will follow “else block“.

if…else Ladder

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 neither condition1 nor condition2 is true
  }

Live Example :

<html>
<body>
<script type="text/javascript">
var d = new Date();
var time = d.getHours();
if (time < 10)
  {
  document.write("<b>Good morning</b>");
  }
else if(time < 16 && time > 10)
  {
  document.write("<b>Good Afternoon</b>");
  }
else
  {
  document.write("<b>Have a good day</b>");
  }
</script>
</body>
</html>

Explanation :

  1. Suppose current time is less than 10 then “Good Morning” will be printed.
  2. If current time is in between 10 and 16 then “Good Afternoon” will be printed.
  3. If both condition fails then else block is followed.

You may like these articles :