JavaScript Conditional Statements


In javascript, a condition is evaluated by conditional statements and it is decided which code will be executed if the condition is true or false. Below are three different types of conditional statements that we can use in our program depending on the requirement.

  • If Statement
  • If else statement
  • If else if statement

JavaScript If statement

If the condition given in this statement becomes true, then the code written inside the bracket is executed and the code inside the bracket is omitted if the condition is false.

Syntax

if (condition){
// code to be executed 
}

Example

<script type="text/javascript">
var a = 10; 
var b = 25;
if(a < b){
  document.write("a is less than b");
}
</script>

JavaScript If else statement

In this statement, if the true condition is executed as if, then the bracket code is executed, but if it is false, the otherwise part is executed. That is, in this statement, we can write code for both true and false conditions.

Syntax

if (condition){
// code to be executed if condition is true 
}
else{
// code to be executed if condition is false
}

Example

<script type="text/javascript">
var a = 10; 
var b = 25;
if(a < b){
  document.write("a is less than b");
}else
{
  document.write("a is not less than b");
}
</script>

JavaScript If else if statement

If we want to check more than one condition, we can use the if-else if statement for this.

Syntax

if (condition1){
// code to be executed if condition1 is true 
}
else if(condition2){
// code to be executed if condition2 is true
}
else{
// code to be executed if all conditions are false
}

Example

<script type="text/javascript">
var a = 10;
var b = 15;

if(a > b){
  document.write("a is greater than b");
}
else if(a < b){
  document.write("a is less than b");
}
else{
  document.write("a is equal to b");
}
</script>