15 If Statement Examples: A Comprehensive Guide To Conditional Flow

In programming, the if statement is a fundamental concept that allows developers to control the flow of their code based on certain conditions. It is a powerful tool for creating dynamic and interactive applications. In this guide, we will explore 15 examples of if statements, covering various scenarios and use cases. By understanding these examples, you'll gain a comprehensive understanding of how to utilize conditional flow effectively in your programming projects.
Simple If Statement

The most basic form of an if statement checks a condition and executes a block of code if the condition is true. Here's an example:
if (condition) {
// Code to execute if the condition is true
}
For instance, if we want to check if a number is greater than 10 and print a message accordingly:
number = 15
if (number > 10) {
console.log("The number is greater than 10");
}
If-Else Statement

An if-else statement allows you to specify an alternative block of code to execute if the initial condition is false. This is useful for providing different outcomes based on the condition.
if (condition) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}
For example, if we want to check if a number is even or odd and print the result:
number = 7
if (number % 2 === 0) {
console.log("The number is even");
} else {
console.log("The number is odd");
}
Nested If Statements

You can nest if statements within each other to create more complex conditional logic. This allows for checking multiple conditions and executing different code blocks based on the outcomes.
if (condition1) {
// Code to execute if condition1 is true
if (condition2) {
// Code to execute if both condition1 and condition2 are true
}
}
Consider the following example, where we check if a person is an adult (age > 18) and if they are an adult, we further check if they are a senior citizen (age > 60) and print the appropriate message:
age = 25
if (age > 18) {
console.log("The person is an adult");
if (age > 60) {
console.log("The person is a senior citizen");
}
}
If-Else-If Ladder

An if-else-if ladder is a sequence of if-else statements where each condition is checked one after the other. This structure is useful when you have multiple conditions to evaluate and want to execute specific code for each condition.
if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition2 is true
} else if (condition3) {
// Code to execute if condition3 is true
} else {
// Code to execute if none of the conditions are true
}
For instance, if we want to check a person's age and print a message based on different age categories:
age = 30
if (age < 18) {
console.log("You are a minor");
} else if (age >= 18 && age < 60) {
console.log("You are an adult");
} else if (age >= 60) {
console.log("You are a senior citizen");
}
Using Logical Operators

You can combine multiple conditions using logical operators like AND (&&) and OR (||) to create more complex if statements. These operators allow you to evaluate multiple conditions at once.
AND Operator

if (condition1 && condition2) {
// Code to execute if both condition1 and condition2 are true
}
For example, if we want to check if a student has passed both math and science exams:
mathPassed = true;
sciencePassed = true;
if (mathPassed && sciencePassed) {
console.log("The student has passed both exams");
}
OR Operator

if (condition1 || condition2) {
// Code to execute if either condition1 or condition2 is true
}
In this example, we check if a user has access to either the admin or user role:
isAdmin = true;
isUser = false;
if (isAdmin || isUser) {
console.log("The user has access");
}
Short-Circuit Evaluation

Short-circuit evaluation is a feature where the evaluation of an expression stops as soon as the outcome is determined. This can be useful for optimizing code and avoiding unnecessary computations.
AND Operator Short-Circuit

if (condition1 && evaluateThis()) {
// Code to execute if condition1 is true and evaluateThis() returns true
}
In this example, the function evaluateThis()
is only called if condition1
is true, preventing unnecessary computations.
OR Operator Short-Circuit

if (condition1 || evaluateThis()) {
// Code to execute if condition1 is true or evaluateThis() returns true
}
Similarly, in this case, evaluateThis()
is only called if condition1
is false, optimizing the evaluation process.
Using Switch Statement

A switch statement is an alternative to if-else ladders and is useful when you have multiple conditions that result in different outcomes. It provides a more readable and concise way to handle such scenarios.
switch (expression) {
case value1:
// Code to execute if the expression matches value1
break;
case value2:
// Code to execute if the expression matches value2
break;
default:
// Code to execute if none of the cases match
}
For instance, if we want to check a person's gender and print a personalized message:
gender = "Male";
switch (gender) {
case "Male":
console.log("Welcome, Sir!");
break;
case "Female":
console.log("Welcome, Ma'am!");
break;
default:
console.log("Welcome, Guest!");
}
Ternary Operator

The ternary operator is a concise way to write if-else statements. It allows you to evaluate a condition and provide an outcome based on the result in a single line of code.
(condition) ? trueExpression : falseExpression;
Here's an example of using the ternary operator to check if a number is positive or negative and print the result:
number = -5;
result = (number > 0) ? "Positive" : "Negative";
console.log(result); // Output: Negative
Using Conditional Operator

The conditional operator, also known as the ternary operator, can be used to assign a value to a variable based on a condition. It is a more flexible alternative to the ternary operator.
variable = condition ? trueValue : falseValue;
For example, if we want to set a discount based on the total purchase amount:
total = 100;
discount = (total > 50) ? 10 : 5;
console.log(discount); // Output: 10
Chained Conditional Statements

You can chain multiple conditional statements together to create complex logic. This is particularly useful when you have nested conditions and want to avoid deep indentation.
let result = (condition1) ? trueExpression1 : (condition2) ? trueExpression2 : falseExpression;
In this example, we check if a number is positive, negative, or zero and print the result:
number = -3;
result = (number > 0) ? "Positive" : (number < 0) ? "Negative" : "Zero";
console.log(result); // Output: Negative
Using Boolean Expressions
Boolean expressions are used to evaluate conditions and return a boolean value (true or false). These expressions are commonly used in if statements to determine the flow of the program.
if (booleanExpression) {
// Code to execute if the booleanExpression is true
}
For instance, if we want to check if a number is divisible by 3 and print a message:
number = 9;
isDivisible = number % 3 === 0;
if (isDivisible) {
console.log("The number is divisible by 3");
}
Using Loops with If Statements
You can combine if statements with loops to iterate over a collection of data and perform conditional operations on each element.
If Statement with For Loop

for (let i = 0; i < array.length; i++) {
if (condition) {
// Code to execute for each element in the array if the condition is true
}
}
In this example, we check if each element in an array is even and print the result:
const numbers = [2, 5, 8, 12];
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 === 0) {
console.log(numbers[i] + " is even");
}
}
If Statement with While Loop

while (condition) {
if (anotherCondition) {
// Code to execute while the condition is true and anotherCondition is also true
}
}
Here, we use a while loop to repeatedly check if a number is a power of 2 and print the result:
number = 16;
while (number > 0) {
if (number % 2 === 0) {
console.log(number + " is a power of 2");
number /= 2;
} else {
break;
}
}
Using If Statements with Functions
You can use if statements within functions to control the flow of the function's execution. This allows you to create functions that behave differently based on certain conditions.
function myFunction(condition) {
if (condition) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}
}
In this example, we create a function that checks if a number is prime and returns true or false:
function isPrime(num) {
if (num < 2) {
return false;
}
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
Using If Statements with Arrays
If statements can be used with arrays to filter, map, or perform other operations on the elements based on specific conditions.
Filtering an Array

const filteredArray = array.filter(element => {
if (condition) {
return true;
} else {
return false;
}
});
For instance, we can filter an array of numbers to keep only the even numbers:
const numbers = [2, 5, 8, 12];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // Output: [2, 8, 12]
Mapping an Array

const mappedArray = array.map(element => {
if (condition) {
return transformedElement;
} else {
return element;
}
});
In this example, we map an array of numbers and double the value if the number is even:
const numbers = [2, 5, 8, 12];
const doubledNumbers = numbers.map(num => {
if (num % 2 === 0) {
return num * 2;
} else {
return num;
}
});
console.log(doubledNumbers); // Output: [4, 5, 16, 24]
Using If Statements with Objects
If statements can be used with objects to perform operations based on specific properties or conditions.
const object = {
property: value,
// ...
};
if (condition) {
// Code to execute if the condition is true and perform operations on the object
}
For example, if we have an object representing a person and we want to check if they are an adult based on their age:
const person = {
name: "John",
age: 22,
};
if (person.age >= 18) {
console.log(person.name + " is an adult");
}
Conclusion
In this comprehensive guide, we explored various examples of if statements, covering simple if-else statements, nested if statements, if-else ladders, logical operators, short-circuit evaluation, switch statements, ternary operators, and more. By understanding these concepts and their applications, you'll be well-equipped to utilize conditional flow effectively in your programming endeavors. Remember that conditional statements are a powerful tool for creating dynamic and interactive programs, allowing you to control the execution of your code based on specific conditions.
FAQ
What is an if statement in programming?

+
An if statement is a programming construct that allows you to control the flow of your code based on certain conditions. It enables you to execute specific blocks of code if a condition is met.
How do I use the if-else statement in my code?

+
The if-else statement is used to provide an alternative block of code to execute if the initial condition is false. It is written as if (condition) { /* code to execute if true / } else { / code to execute if false */