Conditional statements in JavaScript

ยท

2 min read

What is conditional statements?

Conditional statements are constructs in programming that allow code to make decisions based on specific conditions or expressions. They let the program execute certain pieces of code when certain conditions are met, and potentially different pieces of code when conditions are not met.

In simple terms, they allow the program to "choose" between different actions depending on whether a condition is true or false.

Types of conditional statements:

1. If Statement

The if statement runs a block of code if the condition evaluates to true.

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

Example:

let name = "Joe";
if (name === "Joe") {
  console.log(`Hello ${name}`);
}

2. Else Statement

The else statement runs a block of code if the condition in the if statement is false.

if (condition) {
  // Code if true
} else {
  // Code if false
}

Example:

let score = 30;
if (score >= 80) {
  console.log("You passed!");
} else {
  console.log("You failed.");
}

3. Else If Statement

The else if statement checks multiple conditions. If the first condition is false, it moves to the next condition.

if (condition1) {
  // Code if condition1 is true
} else if (condition2) {
  // Code if condition1 is false and condition2 is true
} else {
  // Code if both are false
}

Example:

var num = -10;
if (num > 0) {
    console.log("Number is positive.");
} else if (num < 0) {
    console.log("Number is negative.");
} else {
    console.log("Number is zero.");
}

4. Switch Statement

The switch statement allows you to evaluate a variable and compare it to different values, running the code block that matches.

switch(expression) {
  case value1:
    // Code if expression matches value1
    break;
  case value2:
    // Code if expression matches value2
    break;
  default:
    // Code if no match
}

Example:

 let grade = prompt("Enter a grade")

switch(grade){
         case 's':
             console.log("excellent");
             break;
         case 'a':
             console.log("very good");
             break;
         case 'b':
             console.log("good ");
             break;
         case 'c':
             console.log("fair");
             break;
         case 'd':
             console.log("poor");
             break;
         case 'f':
             console.log("Fail");
             break;
}

5. Ternary Operator (Shortened Conditional)

The ternary operator is a shorthand for if-else statements.

condition ? expressionIfTrue : expressionIfFalse;

Example:

let letter = prompt("Enter the capital letter")
console.log((letter>="A" && letter <="Z")?`${letter} is a capital letter`:`${letter} is not Capital`)
ย