The english if conditional is a programming construct that executes different code blocks based on whether a specified condition evaluates to true or false. It forms the foundation of decision-making in code.
An if conditional checks a boolean expression. If the expression is true, the code inside the if block runs. Most languages also support else and elif (else if) clauses to handle alternative outcomes.
For example, this Python code checks if a number is positive:
number = 5
if number > 0:
print("The number is positive")
else:
print("The number is not positive")
| Component | Description | Example |
|---|---|---|
| Condition | Boolean expression evaluated for truthiness | x > 5 |
| If Block | Code executed when condition is true | print("Greater than 5") |
| Else Block | Code executed when condition is false | print("5 or less") |
| Elif Block | Additional conditions checked if initial condition is false | elif x == 5: print("Equal to 5") |
Programmers use if conditionals for:
A common mistake is nesting too many conditionals, which creates hard-to-read "pyramids of doom." Many languages offer alternatives like switch-case statements for multiple conditions.
Many beginners confuse if conditionals with while loops. While both control program flow, conditionals make single decisions while loops repeat code blocks until a condition changes.
Another confusion point is assuming all conditions evaluate to strictly true or false. Some languages have "truthy" and "falsy" values where non-boolean expressions can be evaluated as conditions.
This JavaScript function determines shipping costs based on order size:
function calculateShipping(cost) {
if (cost > 100) {
return 0; // Free shipping for large orders
} else if (cost > 50) {
return 5; // Discounted shipping
} else {
return 10; // Standard shipping rate
}
}
console.log(calculateShipping(75)); // Returns 5
When called with 75, this function returns 5 because the second condition (cost > 50) evaluates to true.