Learn Programming Fundamentals
1 Programming Fundamentals
2 Variables Data Types
4 Strings
5 Arrays
6 Objects
8 Functions
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) }
if
keyword precedes a condition enclosed within parentheses.{}
is executed.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.
let age = 15; if (age >= 18) { console.log("You are eligible to vote."); } else { console.log("You are not eligible to vote."); }
age
variable is assigned a value of 15.if
statement verifies whether age
is greater than or equal to 18 (the condition).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.