20 Feb JavaScript – Decision Making Statements
With decision-making statements in JavaScript, easily take decisions based on different conditions. The following are the decision-making statements in JavaScript:
- if statement
- if…else statement
- if…elseif..else statement
if statement
The if statement in JavaScript executes the code if the condition is true. The following is the syntax of the if statement:
1 2 3 4 5 |
if (condition) { // statement(s) gets executed if the condition is True } |
Let us see an example to implement the if statement in JavaScript:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<!DOCTYPE html> <html> <body> <h1>if statement</h1> <h2>Vote Status</h2> <p id="test"></p> <script> let age = 20 // Check the vote eligibility if (age > 18) { document.getElementById("test").innerHTML = "The Candidate is Eligible to Vote"; } </script> </body> </html> |
Output
if…else statement
The if…else statement in JavaScript executes some code if the condition is true and another code if
the condition is false. The false condition comes under else. The following is the syntax of the if…else statement:
1 2 3 4 5 6 7 8 |
if (condition) { // code will execute if the condition is true } else { // code will execute if the condition is false } |
Let us see an example to implement the if…else statement in JavaScript:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<!DOCTYPE html> <html> <body> <h1>if...else statement</h1> <h2>Vote Status</h2> <p id="test"></p> <script> let age = 15 // Check the vote eligibility if (age > 18) { result = "The Candidate is Eligible to Vote" } else { result = "The Candidate is not Eligible to Vote" } document.getElementById("test").innerHTML = result; </script> </body> </html> |
Output
if…else if…else statement
The if…else if…else statement in JavaScript executes code for different conditions. If more than 2 conditions are true, you can use else for the false condition.
The following is the syntax of the if…else if…else statement:
1 2 3 4 5 6 7 8 9 10 11 |
if (condition1) { // code will execute if the condition is true } else if (condition2) { // code will execute if condition2 is true } else if (condition3) { // code will execute if condition3 true } else { // code will execute if all the above given conditions are false } |
Let us see an example to implement the if…else if…else statement in JavaScript:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<!DOCTYPE html> <html> <body> <h1>if...else if...else statement</h1> <h2>Vote Status</h2> <p id="test"></p> <script> let age = 15 // Check the vote eligibility if (age > 18) { result = "The Candidate is Eligible to Vote" } else if (age == 18){ result = "Age is 18, therefore the candidate can vote." } else { result = "Age is less than 18, therefore the candidate cannot vote." } document.getElementById("test").innerHTML = result; </script> </body> </html> |
Output
No Comments