Skip to content

Latest commit

 

History

History
104 lines (80 loc) · 2.47 KB

File metadata and controls

104 lines (80 loc) · 2.47 KB

09 Conditions

Conditions are used to make decisions in code. They allow a program to execute different blocks of code based on different conditions.

09.1 If

The if statement is used to execute a block of code only when a condition is true.

let age = 18;
if (age >= 18) {
  console.log("You are eligible to vote");
}

Note: If the condition evaluates to false, the code inside the if block will not run.

09.1.1 If Else

The if else statement is used when you want to run one block of code if the condition is true and another block if it is false.

let age = 16;
if (age >= 18) {
  console.log("You are eligible to vote");
} else {
  console.log("You are not eligible to vote");
}

Note: else runs only when the if condition fails.

09.1.2 Nested If Else

A nested if else is an if else statement placed inside another if or else block. It is used when multiple conditions depend on each other.

let age = 20;
let hasLicense = true;
if (age >= 18) {
  if (hasLicense) {
    console.log("You can drive");
  } else {
    console.log("You need a license to drive");
  }
} else {
  console.log("You are underage");
}

Note: Nested if else is useful when conditions are hierarchical and must be checked step by step.

09.2 Ternary Operator

The ternary operator is a shorter way to write an if else statement. It is mostly used for simple conditions.

let age = 20;
let result = age >= 18 ? "Eligible" : "Not Eligible";
console.log(result); // Eligible

Note: Use the ternary operator only when the logic is simple and easy to read.

09.2.1 Nested Ternary

A nested ternary is a ternary operator placed inside another ternary operator.
It allows you to handle multiple conditions in a single expression.

let score = 75;
let grade = score >= 90 ? "A" : score >= 75 ? "B" : score >= 60 ? "C" : "Fail";
console.log(grade); // B

09.3 Switch

The switch statement is used when you need to compare one value against multiple possible cases.

let currentDay = 3;
switch (currentDay) {
  case 1:
    console.log("Monday");
    break;
  case 2:
    console.log("Tuesday");
    break;
  case 3:
    console.log("Wednesday");
    break;
  default:
    console.log("Invalid day");
}

Note:

  • break stops the execution of the switch block.
  • Without break, execution will continue to the next case (fall-through).
  • default runs when no case matches.