Home Courses Conditional Statements Explained - if, else, else if & switch

Conditional Statements Explained - if, else, else if & switch

Some operators are still left, but before learning them, it’s important to understand conditional statements, because many operators depend on them.


What are Conditional Statements?

Conditional statements help in decision making in code.

Real-life examples:

  1. If it is raining → we stay inside
  2. If the weather is good → we go outside
  3. If age ≥ 18 → you can vote

In programming, we use conditions like this:

if(condition){
// code runs if condition is true
}


if Statement

This is the most basic conditional statement.

Example:

let age = 20;

if(age >= 18){
alert("You can vote");
}

If the condition is true, the code runs. If false, nothing happens.


if...else Statement

Used when you want an alternative action.

Example:

let age = 10;

if(age >= 18){
alert("You can vote");
}else{
alert("You cannot vote");
}

If the condition is true, the first block runs. Otherwise, the else block runs.


else if Statement

Used when you have multiple conditions.

Example (Grading System):

const marks = 85;

if(marks >= 80){
console.log("Grade A");
}else if(marks > 60 && marks < 80){
console.log("Grade B");
}else if(marks > 45 && marks < 60){
console.log("Grade C");
}else{
console.log("Grade D");
}

This is useful when you want to check several conditions one by one.


switch Statement

Used when you have multiple fixed values.


Example (Days of Week):

let day = 4;

switch(day){
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
case 4:
console.log("Thursday");
break;
case 5:
console.log("Friday");
break;
case 6:
console.log("Saturday");
break;
case 7:
console.log("Sunday");
break;
default:
console.log("Wrong Input");
}


Important Points

  1. Always use break in a switch statement.
  2. Without it, all cases after the matched case will execute.
  3. Use default to handle invalid inputs.


When to Use What?

Situation
Single conditionif
Two conditionsif...else
Multiple conditionselse if
Fixed values/optionsswitch


Interview Tip

  1. Conditional statements are used for decision making.
  2. Use switch when you have many fixed values like menu options or days.


Share this lesson: