Javascript if else TUTORIAL


Comparison Operators and if else


Comparison operators are used for comparing the value of the variables. In conjunction with if and else statements they make up the most important fabric of the javascript programming language. Let us take an example

  1. <html>
  2. <body>
  3. <script type="text/javascript">
  4. <!--
  5. /*
  6. ********************************************************
  7. Example if ...else and conditional operator
  8. ********************************************************
  9. */
  10. var d = new Date();
  11. var time = d.getHours();
  12. if (time < 10)
  13. {
  14. document.write("Good morning!");
  15. }
  16. else
  17. {
  18. document.write("Good day!");
  19. } //-->
  20. </script>
  21. </body>
  22. </html>
If you run the above script it should display "good morning" or "good evening" depending upon the time when you play this code. The < ( less than) is a conditional operator.

You can try to experiment it online at the following link ( opens in a new window).

Javascript if else Example

The table below gives a list of the conditional operators.

Operator Description Example
== is equal to 5==8 returns false
=== is equal to (checks for both value and type) x=5
y="5"

x==y returns true
x===y returns false

!= is not equal 5!=8 returns true
> is greater than 5>8 returns false
< is less than 5<8 returns true
>= is greater than or equal to 5>=8 returns false
<= is less than or equal to 7<=8 returns true



Conditional Statements


JavaScript has the following conditional statements, that are used to perform different actions for different decisions.

if else Statements

< If the condition is true one block of statements ( if) is executed, otherwise else block is executed.
if (condition)
{
code to be executed; //if condition is true
}
else
{
code to be executes; // if condition is false
}


The example at the top of the page showed the if else construct.

if Statements


Use if statement if you want to execute some code only if a specified condition is true. The syntax of i f statement is as follows
if (condition)
{
code to be executed; //if condition is true
}

The example below shows an if construct.

  1. <html>
  2. <body>
  3. <script type="text/javascript">
  4. <!--
  5. /*
  6. ********************************************************
  7. Example If else construct
  8. referencedesigner.com
  9. ********************************************************
  10. */
  11. var d = new Date();
  12. var time = d.getHours();
  13. if (time < 12)
  14. {
  15. document.write("It is not past noon yet");
  16. }
  17.  
  18. document.write("The tutorial by referencedesigner.com");
  19. //-->
  20. </script>
  21. </body>
  22. </html>

Exercises


1. Given three numbers x, y and z find and print the greatest of the three numbers by making use of the if then else statements. Try this example by making changes here . Then compare you solution with the solution here .