JavaScript If…Else Statements

If Statement:

Syntax :

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

if condition will be true. then and then only code block inside if will be executed.

Example:

if (age>18 )

{

      alert(‘you are not a child’);

}

If…else Statement

This is also same as if statement but in addition to if condition get not satisfied else code block will be executed whether checking of any condition.

Syntax: 

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

Example:

if(age >18)

{

                 alert(‘you are not child’);

}

else

{

                 alert(‘you are a child’);

}

If…else if…else Statement:

Syntax:

 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
}

Example:

if(age >18)

{

                 alert(‘you are not child’);

}

else if(age > 50)

{

                 alert(‘you are a old guy.’);

}

else

{

                  alert(‘you are a child’);

}

Leave a Reply