Web Programming TutorialsJavascript Conditionals

Javascript Conditionals

Today we will be learning conditional statements in javascript. Conditional statements are nothing but decision making statements. Using these statements we can decide our task i.e. what to do for a particular situation. In conditional statements we are going to learn if statement, if – else statement, if – else if statement and switch statement.

Let’s start by creating a simple html document. Follow the steps.

  1. Create a new folder on desktop named “sec3_ch6”.
  2. Then open a new notepad++ document and save it as “conditionals.html” in the newly created folder “sec3_ch6”.
  3. Write the following code in the document “conditionals.html” and save it.
  4. <!DOCTYPE html>
    <html>
    <head>
    <title>Javascript Conditionals</title>
    </head>
    <body>
    </body>
    </html>
    

    The page “conditionals.html” when opened in the browser will look like this:

    initial_output_before_javascript
    fig 1

  5. Learn to use conditional statements.
    1. If statement:
      • In the if conditional statement, a condition is checked and the statements in its curly braces are executed only if the condition is evaluated to true.
      • Syntax of if statement is shown below:
      • if(condition)
        {
        ---- statement/statements;
        }
      • Let us demonstrate if statement by writing the following code in body section of “conditionals.html” document.
      • <script>
        	var x=5;
        	if(x==5)
        	{
        		alert('Yes it is');
        	}
        </script>
      • In the above code we have declared a variable x with a value 5 assigned to it.
      • Here, if conditional statement is used to check the condition and take the desired decision.
      • Condition to be checked in if statement is x==5. This condition tells us to check whether the value assigned to x is equal to 5.
      • Here, == is the comparison operator. Its task is to compare two entities.
      • On the other hand = is the assignment operator. Its task is just to assign its right hand side value to its left hand side entity.
      • In this case, if the condition x==5 evaluates to true, the statement in curly brace will popup an alert message saying “Yes it is”.
      • The output is shown below:
      • if_statement_output
        fig 2

      • The output above is shown if the condition is true.
      • But if the condition doesn’t evaluate to true i.e. if x is assigned value 4 and condition is x==5, no output will be shown, page will look like the same page shown in fig 1.
      • If we want that even if the condition is false, some information be shown to us; we should use else statement along with if statement.
    2. If–else statement:
      • In the if-else conditional statement, a condition is checked and the statements in its curly braces are executed only if the condition is evaluated to true. And if the condition is evaluated to false, the statements in the else part are executed.
      • Syntax of if statement is shown below:
      • if(condition)
        {
        ---- statement/statements;
        }
        else
        {
        ---- statement/statements;
        }
      • Let us demonstrate if-else statement by writing the following code in body section of “conditionals.html” document.
      • <script>
        	var x=4;
        	if(x==5)
        	{
        		alert('Yes it is');
        	}
        	else
        	{
        		alert('No it is not!');
        	}
        </script>
        
      • Here, if part of the code is same as explained above for if statement.
      • We know that if the condition evaluates to true the statements in if block will be executed (the statements in the curly braces of if statement are called as if block statements).
      • But if the condition evaluates to false, the statements in the curly braces of else statement are executed i.e. if the condition is false, else part is executed.
      • In this case, value of variable x is 4 and condition in if statement is x==5. This condition will definitely execute to false and else part of the statement will be executed giving an alert message “No it is not!”.
      • The output is shown below:
      • if_else_statement_output
        fig 3

      • The output of false condition is shown above.
      • We can use all the relational operators such as <,>,==,!=,<=,>= and logical operators such as &&(AND), ||(OR) and !(NOT) in the condition to be evaluated.
      • Some of the examples of if conditions shown below. Consider x=6.
        • if(x>5) —– output : Yes it is
        • if(x<5) —– output : No it is not!
        • if(x<=5) —– output : No it is not!
        • if(x>=5) —– output : Yes it is
        • Now consider x=4.

        • if(x>5 && x<10) —– output : No it is not! –> when we use && (AND) operator in a condition, both the conditions need to be true compulsorily, if it is not so the condition is treated as false.
        • if(x>5 || x<10) —– output : Yes it is –> when we use || (OR) operator in a condition, at least one condition need to be true compulsorily, if it is not so the condition is treated as false.
        • if(x>5 && x<10 && x<0) —– output : No it is not! –> in this example 2 conditions x>5 and x<0 are false and only one condition x<10 is true. Since all the conditions are not true the output is “No it is not”.
      • Using if or if-else we can check only one condition in the if statement, but to check number of possible conditions we need to use if-else if statement.
    3. If–else if statement:
      • In the if-else if conditional statement, multiple conditions are checked. A condition is checked and the statements in its curly braces are executed only if the condition is evaluated to true. If the first condition is evaluated to false, the next condition in the else if part is checked, if it is false, again next condition in next else if part is checked. This can continue with number of levels of if-else if ladder. In this, even if at least one condition evaluates to true, statements of the true condition if block will be executed and the control will stop checking further conditions. But finally if not even one condition evaluates to true, the statements in the else part are executed.
      • Syntax of if-else if statement is shown below:
      • if(condition)
        {
        ---- statement/statements;
        }
        else if
        {
        ---- statement/statements;
        }
        else if
        {
        ---- statement/statements;
        }
        else
        {
        ---- statement/statements;
        }
      • This conditional statement is also known as if-else if ladder.
      • Let us demonstrate if-else if statement by writing the following code in
        <script>---</script>

        in body section of “conditionals.html” document below if-else code written previously.

      • var color="black";
        if(color=="red")
        {
        	document.write("the color is 'red'");
        }
        else if(color=="blue")
        {
        	document.write("The color is 'blue'");
        }
        else
        {
        	document.write("The color is not 'red' or 'blue'");
        }
        
      • In this example, a variable named color is declared and a value black is assigned to it.
      • Next a condition color==red is checked in the if statement. It evaluates to false since the value of variable color does not match the value red.
      • Now, control goes to the else if condition below and checks the condition color==blue. This condition also evaluates to false since the value of variable color does not match the value blue.
      • Next, the control goes to else part and executes the else part statement document.write(“The color is not ‘red’ or ‘blue'”);
      • This happened because, all the conditions checked evaluated to false.
      • So the output The color is not ‘red’ or ‘blue’ will be displayed in the browser.
      • The output is shown below:
      • if_else_if_statement_output_1
        fig 4

      • Now let’s change the value of variable color declared above from black to red and reload the page.
      • The output obtained is shown below:
      • if_else_if_statement_output_2
        fig 5

      • Here, the color variable has value “red”. So when the condition in first if statement is checked, it evaluates to true and the statement in its block is executed.
      • Now, since the condition has been matched at the first attempt itself, rest of the conditions will not be checked i.e. the control will come out of the if-else if block.
      • This was if-else if ladder.
      • Now, when we use if-else if ladder it is very confusing to keep track of all the else if blocks. A more simplified way of doing the same task of if-else if ladder i.e. checking multiple conditions is switch case statement. Switch case statement is an organized form of if-else if statement.
    4. Switch case statement:
      • In switch case statement, the variable or the expression whose value is to be matched is put in the switch statement. This switch block contains various case statements to which the value of the variable or expression is matched. If any of the case statement value is matched to the value to be matched, the statements in the case are executed. You can understand that this case statements are same as else if statements in if-else if ladder. If no case is matched, default statement is executed.
      • Syntax for switch case statement is shown below:
      • switch(variable/expression)
        {
           case value1 :  
                        -----      //statement/statements 
                        break;
           case value2 :
                        -----     //statement/statements
                        break;
           -
           -
           -
           default :    -----   //statement/statements 
                        break;
        }
      • After every case statement break statement is compulsory. If you forget to give a break statement after any case statement, the next case statement will also be executed with the desired one.
      • The default statement in switch case statement is optional.
      • Write the following code in the script tag in body section below if-else if code:
      • var y=4;
        switch(y)
        {
          case 2: 
                 document.write('y is 2');
        	 break;
          case 5:
                 document.write('y is 5');
                 break;
          default:
                 document.write('y is not 2 or 5');
                 break;
        }
        
      • In the above code, variable y is declared with value 4 assigned to it and this variable is put in the switch statement.
      • This value of variable y is matched to the value 2 of the first case.
      • It did not match to 4, so control is passed to next case and again the value 5 is matched to variable y value.
      • Here also value did not match.
      • Now control moves further and executes the default statement. If no case is matched, the default statement is executed if written.
      • The output is shown below:
      • switch_case_output_1
        fig 6

      • You can have any number of case statements we want in the switch case statement.
      • Now, if you change the value of y in the above code to 5, the following output will be obtained:
      • switch_case_output_2
        fig 7

      • Now let us demonstrate switch case with some sensible example.
      • Write the following code in the script tag in body section:
      • var day=new Date().getDay();
        switch(day)
        {
        	case 0: d="Today it's Sunday";
        		break;
        	case 1: d="Today it's Monday";
        		break;
        	case 2: d="Today it's Tuesday";
        		break;
        	case 3: d="Today it's Wednesday";
        		break;
        	case 4: d="Today it's Thursday";
        		break;
        	case 5: d="Today it's Friday";
        		break;
        	case 6: d="Today it's Saturday";
        		break;
        }
        alert(d);
        
      • The above code finds the day of weak from current date.
      • In the above code, getDay() method of Date class object is used to obtain today’s current date.
      • It returns values from 0 to 6 that represent Sunday, Monday and so on upto Saturday respectively.
      • This value is stored in the variable day and passed to switch statement.
      • Whichever case is matched, the output is stored in the variable d.
      • This output is then displayed in an alert message when the control comes out of the switch block.
      • The output is shown below:
      • switch_case_output_3
        fig 8

Thus we finished studying conditional statements.

Previous articleJavascript Functions
Next articleJavascript Events

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -