Rabu, 04 Juni 2025

Conditional Statements, AND (&&), and OR (||) in Programming

| Rabu, 04 Juni 2025

Conditional statements are one of the most powerful features in programming. They allow your code to make decisions based on certain conditions. This blog will explain how conditional statements work and how logical operators like AND and OR enhance decision-making in your code.

What is a Conditional Statement?

A conditional statement checks if a certain condition (or set of conditions) is true or false, and then performs different actions based on that result.

The most common conditional statements are:

if (condition) {
    // code to run if condition is true
} else {
    // code to run if condition is false
}

For example:

let age = 20;

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

Using Logical Operators: && (AND) and || (OR)

You can combine multiple conditions using logical operators.

AND (&&)

The AND operator returns true only if all conditions are true.

if (age >= 18 && age <= 65) {
    console.log("You are eligible to work.");
}

In this case, both conditions must be true: age must be at least 18 and not more than 65.

OR (||)

The OR operator returns true if at least one of the conditions is true.

let day = "Saturday";

if (day === "Saturday" || day === "Sunday") {
    console.log("It’s the weekend!");
}

Here, if the day is either Saturday or Sunday, the message is printed.


Related Posts

Tidak ada komentar:

Posting Komentar