Conditionals Statements and Boolean Logical Operator in JavaScript

Everything in our day to day life is impacted by conditions. Similarly in Java Script too conditions play a vital role in code execution and its structure. Every JS function must be designed as per the condition of the work we are looking to be done by it. There are many conditions in which the code can be written and simultaneously a code can also be written in many ways following a similar condition. We will see few e.g. below to understand this in a better way but before that lets understand few conditional statements.

If, else, else-if and switch statements in JavaScript :

The word if and else itself states it clearly that certain things to be done only if following rule is fulfilled Or else don’t do it or do something else.

Suppose if you want to do something only in any particular condition then you use the if statement. These are used for much complicated functions with multiple conditions as are easy to understand and maintain that switch.

If statement

Example:

If we want an alert “Yay its Banana” only if the fruit selected is Apple.

      var fruit = “Banana”;

      if(fruit == ‘Banana’){

      alert(‘Yay Its Banana’); //Yay Its Banana

}

If-else statement 

Similarly as above eg. there was just one condition but now if we want more than a condition like alert “Its still Banana” only if Banana is the fruit selected or alert “Are you sure?”

      var fruit = “Orange”;

     if(fruit == ‘Banana’)

    {

     alert(‘Its still Banana);

      }

      else

     {

        alert(“Are you sure ?”); //Are you sure ? (This is because 1st condition is not fulfilled hence second the else one initiated.)

    }

elseif  statement 

Similarly if you want multiple conditions you can use it as many times as you need as per the conditions but if one condition use if, If two conditions use if and else but if more that two conditions use else if further till last one like in e.g. below.

var fruit = “Mango”;
if(fruit == ‘Banana’){
alert(‘Yay Its Banana’);
}
else if(fruit == ‘Appie’)
{
alert(“Have you selected Apple ?”);
}
else if(fruit == ‘Mango’){
alert(“Have you selected Mango ?”); //Have you selected Mango ? (As 3rd condition  fulfilled.)
}
else
{
alert(“Please choose any fruit.”);
}

Nested Conditions:

Nesting means a condition under a condition. Like in the below eg. under first if condition you have 1 more if condition that if color is red and color2 is green change bg color to yellow. Or if color 1 still remains red change bg to red. 

Eg.

<!DOCTYPE html>

<html>

<head>

          <title>JavaScript Basics</title>

          <style type=”text/css”>

                  .bgRed{background-color: red}

                  .bgGreen{background-color: green}

          </style>

</head>

<body>

           <button id=”btn”>Change Color</button>

          

           function colorChanger(){

                    var getColor = prompt(‘Enter a color’);

                    var getColor2 = prompt(‘Enter a color’);

                    if(getColor==’red’){

                        if(getColor2==’green’){

                                   document.body.style.backgroundColor = ‘yellow’;

                        }else{

                                 document.body.style.backgroundColor = ‘red’;

                        }

             }else if(getColor==’blue’ && getColor2==’green’){

             document.body.style.backgroundColor = ‘cyan’;

             }else if(getColor==’red’ && getColor2==’blue’){

             document.body.style.backgroundColor = ‘magenta’;

             }else{

                      document.body.style.backgroundColor = ‘white’;

            }

      }

      document.getElementById(‘btn’).onclick = colorChanger;

       

</body>

</html>

Like if else condition is used for multiple conditions similarly switch is also used for multiple conditions. But in a switch we cannot use assignment operators to define less than or greater than values, we have to give exact values for it and no dynamic values can be given in it.

Example:

<!DOCTYPE html>

<html>

<head>

          <title>JavaScript Basics</title>

          <style type=”text/css”>

                .bgRed{background-color: red}

                .bgGreen{background-color: green}

         </style>

</head>

<body>

          <button id=”btn”>Change Color</button>

         

          function colorChanger(){

                  var getColor = prompt(‘Enter a color’);

                  switch(getColor){

                            case ‘red’:

                  document.body.className = ‘bgRed’;

                  break;

                  case ‘green’:

                  document.body.className = ‘bgGreen’; //Here no assignment

operators are used just values are assigned in case as green, red etc …

                 break;

                 default:

                 alert(‘Enter red or green color’);

                 break;

        }

   }

           document.getElementById(‘btn’).onclick = colorChanger;

</body>

</html>

Why Boolean Logical Operator are important to work with conditions in JavaScript?

  • && (And)

  • || (Or)

  • ! (Not Equal to)

If suppose we have a case where we want a code to be run specifically if we get both of the 2 conditions fulfilled.

Example: I want an alert that “Its correct” only if both of these conditions are fulfilled where in fruit selected is Apple and taste selected is Sweet.

      

       var fruit = “Apple”;
       var taste = “Sweet”;
       if((fruit == ‘Apple’) && (taste == ‘Sweet’)){ //Thats correct Both conditions are must to be fulfilled.
           alert(“Thats correct”);
       }
      
Eg. Similarly if we want any one condition to be fulfilled where in fruits Apple is selected Or if taste Sweet is selected.
     
                    var fruit = “Mango”;
                    var taste = “Sweet”;
                    if((fruit == ‘Apple’) || (taste == ‘Sweet’)){ //One condition is fulfilled
                              alert(“One condition is fulfilled”);
             }
    
Eg. If we want that the selected variable should not have a particular value ie negation condition, we can do it with not equal condition Operator.
    var game = “Cricket”;
    if((fruit != ‘Cricket’){ //Yes its not !
    alert(“Yes its not !”);
}
What are Conditional Operator or Ternary Operator?
It is a short condition to be used in some places. The syntax of conditional operator is:
var result = (condition) ? true expression : false expression;
Example:
var age = 45;
var result = (age == 45)?’You are 45yrs old.’:’You are not 45yrs old.’;
alert(result); //You are 45yrs old.
Summary:
We can use various available conditionals in JavaScript according to the situation. At first glance all the conditions look like an alternative of each other but seriously speaking this is not the case always. As much you will indulge in them more sense you will acquire to use them.
Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s