Cheap VPS & Xen Server


Residential Proxy Network - Hourly & Monthly Packages

JavaScript If statement


The JavaScript if-else statement is used to execute the code whether condition is true or false. There are three forms of if statement in JavaScript.

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

JavaScript If statement

It evaluates the content only if expression is true. The signature of JavaScript if statement is given below.

  1. if(expression){
  2. //content to be evaluated
  3. }

Flowchart of JavaScript If statement

if1

Let’s see the simple example of if statement in javascript.

  1. <script>
  2. var a=20;
  3. if(a>10){
  4. document.write(“value of a is greater than 10”);
  5. }
  6. </script>

Test it Now

Output of the above example

value of a is greater than 10

JavaScript If…else Statement

It evaluates the content whether condition is true of false. The syntax of JavaScript if-else statement is given below.

  1. if(expression){
  2. //content to be evaluated if condition is true
  3. }
  4. else{
  5. //content to be evaluated if condition is false
  6. }

Flowchart of JavaScript If…else statement

if2

Let’s see the example of if-else statement in JavaScript to find out the even or odd number.

  1. <script>
  2. var a=20;
  3. if(a%2==0){
  4. document.write(“a is even number”);
  5. }
  6. else{
  7. document.write(“a is odd number”);
  8. }
  9. </script>

Test it Now

Output of the above example

a is even number

JavaScript If…else if statement

It evaluates the content only if expression is true from several expressions. The signature of JavaScript if else if statement is given below.

  1. if(expression1){
  2. //content to be evaluated if expression1 is true
  3. }
  4. else if(expression2){
  5. //content to be evaluated if expression2 is true
  6. }
  7. else if(expression3){
  8. //content to be evaluated if expression3 is true
  9. }
  10. else{
  11. //content to be evaluated if no expression is true
  12. }

Let’s see the simple example of if else if statement in javascript.

  1. <script>
  2. var a=20;
  3. if(a==10){
  4. document.write(“a is equal to 10”);
  5. }
  6. else if(a==15){
  7. document.write(“a is equal to 15”);
  8. }
  9. else if(a==20){
  10. document.write(“a is equal to 20”);
  11. }
  12. else{
  13. document.write(“a is not equal to 10, 15 or 20”);
  14. }
  15. </script>

Test it Now

Output of the above example

a is equal to 20

Comments

comments