Use of conditional statements in JavaScript

In this article I have described the conditional statements used in JavaScript.
  • 1907

Conditional Statement in JavaScript

  • The condition statement in JavaScript offers a simple way to make a decision in JavaScript.
  • The conditional statement in JavaScript will return either true or false depend upon condition.

If Statement

If statement is used when only a specified condition is executed.

Syntax 

if(condition)
{
//JavaScript code 
}


Example

Lets take an example

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <title>Example of if statement</title>

    <script type="text/javascript">

        var age = 20;

        if (age > 18)

        {

            document.write("<h2>Able for vote </h2>");

        }

</script>

</head>

</html>

Output

f1.jpg

If...else Statement

This statement is used when one condition is true and other is not true.

Syntax

 if(condition)

 {
       
//JavaScript code
 
}
else

{
      //JavaScript code

Example

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <title></title>

    <script type="text/javascript">

        var age = 20;

        if (age > 18) {

            document.write("<h2>Able for vote </h2>");

        } else

        { document.write("<h2>Not to be able for vote </h2>"); }

</script>

</head>

<body>

 

</body>

</html>

Output

fig2.jpg
If...else if....else Statement

When we want to select one of several blocks of code to be executed.

Syntax

if(condition)

{
      //JavaScript code
 }
else if 

{
     //JavaScript code
}
 else 

{
     //JavaScript code
}

Example

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <title>Example of if...else statement</title>

    <script type="text/javascript">

        var age = 18;

        if (age > 18) {

            document.write("<h2>Able for vote </h2>");

        } else if (age = 18) {

            document.write("<h2>Welcome for vote</h2>");

        }

        else

        {

            document.write("<h2>Not to be able for vote </h2>");

        }

</script>

</head>

</html>

Output

fig2.jpg

Further Readings

You may also want to read these related articles :

Ask Your Question 

Got a programming related question? You may want to post your question here

Programming Answers here

© 2019 DotNetHeaven. All rights reserved.