If statement in JS-tutorial
In JavaScript, if statements let you control what code runs based on specific conditions.
This helps make your programs dynamic and responsive.
There are three main types of if statements in JavaScript
if Statement
The simplest conditional, It execute a block of code only if the given condition is true.
Syntax:
This helps make your programs dynamic and responsive.
There are three main types of if statements in JavaScript
- if statement
- if...else statement
- if...else if...else statement
if Statement
The simplest conditional, It execute a block of code only if the given condition is true.
Syntax:
if (condition) { // code runs if condition is true}
Example:
<html>
<body> <script> var a = 20; if (a % 2 == 0) { document.write("a is even number"); } </script></body>
</html>
Output
.webp)
If . . .else Statement
Adds an alternative block that runs if the condition false.
Syntax:
if (condition) { // code runs if condition is true} else { // code runs if condition is false}
Example:
<html>
<body> <script> var a = 20; if (a % 2 == 0) { document.write("a is even number"); } else { document.write("a is odd number"); } </script></body>
</html>
Output
.webp)
if . . .else if . . .else Statement
Used when you have multiple conditions to check in sequence.
Syntax:
if (condition1) { // code runs if condition1 is true} else if (condition2) { // code runs if condition2 is true} else if (condition3) { // code runs if condition3 is true} else { // code runs if none of the above conditions are true}
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
.webp)
Key Point
- if runs when a condition is true.
- if...else adds an alternative when the condition is false.
- if...else if...else checks multiple conditions in order.
- Helps make JavaScript programs dynamic, interactive, and smart.