Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

3 Conditional Structures

3 Intro To If Else

Introduction to the If-Else Statement

Now that we've covered decision-making, comparison operators, and logical operators, it's time to delve into conditional statements like the if-else statement. These statements allow us to write code that executes conditionally based on certain criteria.

The if-else statement is a foundational control flow mechanism in many programming languages. It empowers your program to make decisions and execute different code segments based on whether a condition evaluates to true or false.

Here's a breakdown of how the if-else statement typically operates:

if (condition) {
  // Code to execute if the condition is true
} else {
  // Code to execute if the condition is false (optional)
}
  • The if keyword precedes a condition enclosed within parentheses.
  • If the condition resolves to true, the code block within the first set of curly braces {} is executed.
  • If the condition is false, the code block within the else section (the second set of curly braces {}) is executed.

There are scenarios where you may only need the if segment and can omit the else block:

if (condition) {
  // Code to execute if the condition is true
}

In such cases, only the code within the if block is executed if the condition evaluates to true.

Example in JavaScript:

let age = 15;

if (age >= 18) {
  console.log("You are eligible to vote.");
} else {
  console.log("You are not eligible to vote.");
}
  • In this example, the age variable is assigned a value of 15.
  • The if statement verifies whether age is greater than or equal to 18 (the condition).
  • Since 15 is not greater than or equal to 18, the condition evaluates to false.
  • Consequently, the code within the else block is executed, printing "You are not eligible to vote."

This mechanism of conditional execution is fundamental for building programs that can dynamically respond to varying circumstances.