JavaScript have the following conditional execution in the forms of if..else statement
- if statement: if the condition is true, run the block
1 2 3 |
if ( condition true) { //run this code } |
2. if…else statement : if the condition true, run the if block. if false then run the else block
1 2 3 4 5 |
if (condition false) { // skip } else { //run this code } |
Example Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <p id="div1"></p> <script type="text/javascript"> let x = 10; if (x > 5) { document.getElementById("div1").innerHTML="x is greater than 5"; } else { document.getElementById("div1").innerHTML="x is not greater than 5"; } </script> </body> </html> |
x is greater than 5
3. if..else if..else : check for all condition , whatever condition become true run the respective block and exit. if all condition false , run the else block by default.
1 2 3 4 5 6 7 |
if (condition false) { // skip } else if (condition true){ //run this code } else { //if no condition is true } |
Example Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <p id="div1"></p> <script type="text/javascript"> let x = 10; if (x > 0 && x <= 5) { document.getElementById("div1").innerHTML = "x is less than or equal to 5"; } else if (x > 5 && x <= 10) { document.getElementById("div1").innerHTML = "x is greater than 5 and less than or equal 10"; } else { document.getElementById("div1").innerHTML = "x is greater than 10"; } </script> </body> </html> |
Output: x is greater than 5 and less than or equal 10