if else

Understanding "if else" statement in programming

In programming, the "if else" statement is one of the most commonly used conditional statements. It allows us to execute specific blocks of code based on certain conditions. This statement consists of two parts - the if statement and the else statement. The if statement is executed if a certain condition is true, and the else statement is executed if the condition is false.

Syntax:

// Syntax in JavaScript
if (condition) {
  // code block to be executed if the condition is true
} else {
  // code block to be executed if the condition is false
}

The condition is a boolean expression that evaluates to either true or false. If the condition is true, the code inside the if block will be executed; otherwise, the code inside the else block will be executed.

Example:

// Example in JavaScript
var age = 20;

if (age >= 18) {
  console.log("You are an adult");
} else {
  console.log("You are not an adult");
}

In this example, we have a variable called "age" which is set to 20. The if statement checks if the age is greater than or equal to 18. Since 20 is greater than 18, the code inside the if block will be executed, which prints "You are an adult" to the console.

Multiple Conditions:

We can also use multiple conditions in an "if else" statement using logical operators like AND (&&) and OR (||).

// Example with multiple conditions in JavaScript
var age = 20;
var gender = "male";

if (age >= 18 && gender === "male") {
  console.log("You are a male adult");
} else if (age >= 18 && gender === "female") {
  console.log("You are a female adult");
} else {
  console.log("You are not an adult");
}

In this example, we have added another condition to check the gender of the person. If the age is greater than or equal to 18 and the gender is male, the code inside the first if block will be executed. If the age is greater than or equal to 18 and the gender is female, the code inside the else if block will be executed. If both conditions are false, the code inside the else block will be executed.

Conclusion:

The "if else" statement is a powerful tool in programming that allows us to control the flow of our code based on certain conditions. By using logical operators, we can create more complex conditions and execute different code blocks accordingly.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe