javascript conditional statements

Most of the times, javascript is used to perform operations when certain conditions are true like when the form is submitted you'd like to check if all the required input fields are filled or you'd want to display some informations when a user is using specific browser to view your website. In such cases, if else statement comes handy.

Syntax

<script>
if (condition) {
  action1
} else {
  action2
};  
</script>

In cases, where you have to check more than two conditions, you can use else if statement as shown below.

<script>
if (condition 1) {
  action 1
} else if (condition 2){
  action 2
} else if (condition 3){
  action 3
}else{
  action 4
};  
</script>

Example

<script>
x = 2;
y = 3;
if(x > 2 && y > 2){
  document.write("Both are greater than 2");
}else if (x > 2 || y > 2){
  document.write("One of x or y is greater than 2");
}else{
  document.write("Both are smaller than 2");
}
</script>

0 Like 0 Dislike 0 Comment Share

Leave a comment