What is Computer

Module: M3-R5: Python Programming

Chapter: Ch1 Computer Intro

🔹 Introduction to Conditional Statements

Conditional statements allow JavaScript to perform different actions based on different conditions. They help your code make decisions dynamically.

1. if Statement

Executes a block of code if a condition is true.


let a = 10;
if(a > 5){
  document.write("a is greater than 5"); // Output: a is greater than 5
}

2. if...else Statement

Executes one block of code if the condition is true, otherwise another block.


let b = 3;
if(b > 5){
  document.write("b is greater than 5");
} else {
  document.write("b is not greater than 5"); // Output: b is not greater than 5
}

3. if...else if...else Statement

Used to check multiple conditions sequentially.


let marks = 75;
if(marks >= 90){
  document.write("Grade A");
} else if(marks >= 70){
  document.write("Grade B"); // Output: Grade B
} else {
  document.write("Grade C");
}

4. switch Statement

Executes one block of code from many based on a variable's value.


let day = 3;
switch(day){
  case 1:
    document.write("Monday");
    break;
  case 2:
    document.write("Tuesday");
    break;
  case 3:
    document.write("Wednesday"); // Output: Wednesday
    break;
  default:
    document.write("Another day");
}

5. Ternary Operator

Shorthand for simple if-else statements.


let age = 18;
let status = (age >= 18) ? "Adult" : "Minor";
document.write(status); // Output: Adult

6. Nested if Statement

An if statement inside another if statement for multiple levels of conditions.


let num = 12;
if(num > 0){
  if(num % 2 == 0){
    document.write("Positive Even Number"); // Output: Positive Even Number
  }
}

🧾 Summary of Conditional Statements

This table summarizes all types of conditional statements in JavaScript with example outputs.

Conditional Type Description Example Output
if Statement Executes a block of code if a condition is true. a is greater than 5
if...else Statement Executes one block if true, another if false. b is not greater than 5
if...else if...else Statement Checks multiple conditions sequentially. Grade B
switch Statement Executes one block from many based on a variable's value. Wednesday
Ternary Operator Shorthand for simple if-else. Adult
Nested if Statement An if statement inside another if statement for multiple levels of conditions. Positive Even Number
Quick Links