JavaScript Conditions

JavaScript Condition includes both if else statements and switch case. Conditions are used to check whether given expression is true or not.



IF Statement

JavaScript If statement is used to check whether the given condition is true or not. We can use comparison operators to check condition. The code block inside if condition will work only if following condition is matched. For exp

If Statement Code


        if(condition){
            code to run if condition is true
        }
        

If Condition is very usefull to check whether a number is greater than or equal to another number or not. See example below.


      var age=12;
      if(age<18){
        alert("sorry, you are not eligible")
      }
        

If following condition doesn't match, code block inside if will not work. See example below


      var age=20;
      if(age<18){
        alert("sorry, you are not eligible")
      }
        

Else Statement

Else Statement is an extra block of code used with if condition. In any case if condition fails, code block inside else run.


      if(condition){
            code to run if condition is true
      }
      else{
            code to run if condition is false
      }
         

Else statement can't be used without if statement. If if statement fails, then only else code works. See example below


      var age=20;
      
      if(age<18){
        alert("sorry, you are not eligible")
      }
      else{
        alert("Congrats, you are eligible")
      }
        


Else if Statement

else if statement is used after if statement. Else if works in parallel with if statement, If if condition fails, then only else if statement will be checked.


      if(condition){
            code to run if condition is true
      }
      else if(condition){
            code to run if else-if condition is true
      }
      else{
            code to run both conditions are false
      }
         

Check Positive number using if and else


      var x=20;
      
      if(x==0){
        alert("zero is neither positive, nor negative")
      }
      else if( x>0){
        alert("Number is positive")
      }
      else{
        alert("Number is negative")
      }