JavaScript if/else Statement Syntax

There are the following types of Javascript if/else Statement Syntax.

  1. If Statement
  2. If else statement
  3. if else if statement

If Statement

Javascript if statement is used to check the given condition is true or not. If the condition is true then execute the block of code.

General Syntax
      if (condition) {
  //statement
}
if (condition == true) {
  //execute the code
}
    
Try it now

Source Code

          
            var developmentExperienceYears = 10;
if (developmentExperienceYears > 5) {
  document.write("You are able to open your own startup.");
}          
        
Try it now

If..else Statement

If..else statement is used to execute the block of the code if the certain condition is false.

General Syntax
      if (expression) {
  //The code will be executed if condition is true
} else {
  //The code will be executed if condition is false
}
    
Try it now

Source Code

          
            var itIndustryExperience = 2;
if (itIndustryExperience > 3) {
  document.write("You may try own startup");
} else {
  document.write("Please learn through the mistake.");
}          
        
Try it now

If...else if Statement

This statement is used to check new conditions if the previous condition is false.

General Syntax
      if(condition1){
  //code will be executed if first condition is true
}
else if(condition2){
  //code will be executed iffirst condition is false and second condition is true
}else{
  //code will be executed if first condition is false and second condition is false
}
    
Try it now

Source Code

          
            var itIndustryExperience = 8;
if (itIndustryExperience < 3) {
  document.write("Please learn through the mistake.");
} else if (itIndustryExperience < 6) {
  document.write("You may try for own startup");
} else {
  document.write("You must have to work for own startup");
}          
        
Try it now

The Ternary Operator

It is shorthand of if..else statement and represented by a question mark(?) and takes three operands for checking the condition, a result for true, and a result for false.

var result = (condition) ? value1 : value2;

If the condition is true then value 1 will be returned else value 2 will be returned.

General Syntax
      var result = (condition) ? value1 : value2;
    
Try it now

Source Code

          
            var developmentExperience = 8;
var result = (developmentExperience<5)?"Learn":"Try for startup";          
        
Try it now

Code Explanation

In the above code, the condition is false so the value on the right side of the colon (:) is returned to the variable result;

Web Tutorials

Javascript if/else Statement Syntax
Html Tutorial HTML
Javascript Tutorial JAVASCRIPT
Css Tutorial CSS
Bootstrap 5 Tutorial BOOTSTRAP 5
Bootstrap 4 Tutorial BOOTSTRAP 4