×

Html & Html5

The World's best Software Development Study Portal

Js If-else


These If-else statements are basically used to execute the code whether the condition is true or false. And in Js we have three types of If-else statement, these are as follows :-

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

Js If statement

It only execute the code or content when the particular condition is true.


Syntax

if(expression){

//content to be evaluated

}

Let's understand this by the following example:-

<html>

<body>

<script>

      var a=10;

     if(a>5){

      document.write("value of a is greater than 10");

}

</script>

</body>

</html>

Output of this program

value of a is greater than 10

The condition is true so it gives the right output.



Js If-else statement

It execute the code or content in both case whether the particular condition is true or not.


Syntax

if(expression){

//content to be evaluated if condition is true

}

else{

//content to be evaluated if condition is false

}

Let's understand this by the following example:-

<html>

<body>

<script>

      var a=20;

     if(a%5==0){

      document.write("divisible by 5");

}      else{

      document.write("not divisible by 5");

}

</script>

</body>

</html>

Output of this program

divisible by 5

The condition is true so it gives the right output or if the condition is false too than also it gives the output..



Js if...else if statement

If we are having possibility of many true conditions than we can use this statement.


Syntax

if(expression1){

//content to be evaluated if expression1 is true

}

else if(expression2){

//content to be evaluated if expression2 is true

}

else if(expression3){

//content to be evaluated if expression3 is true

}

else{

//content to be evaluated if no expression is true

}

Let's understand this by the following example:-

<html>

<body>

<script>

var a=20;

if(a==10){

document.write("a is equal to 10");

}

else if(a==15){

document.write("a is equal to 15");

}

else if(a==20){

document.write("a is equal to 20");

}

else{

document.write("a is not equal to 10, 15 or 20");

}

</script>

</body>

</html>

Output of this program

a is equal to 20

Here we are having many possibility of many true conditions, our number can fall in any criterion. So in these type of situation we use this if... else if statement.






JS training insitute | Best IT Training classes in Gurgaon | Web Designing Training Institute