DEV Community

Hiral
Hiral

Posted on

Control Flow in JavaScript: If, Else, and Switch Explained

Control flow determines the order in which instructions run in a program.
By default, programs run line by line but some time we want program to take decision

if Statement
When you want something to happen only if a condition is true

int age = 20;

if(age >= 18) {
    printf("You are an adult.");
}
Enter fullscreen mode Exit fullscreen mode
if else statment
Enter fullscreen mode Exit fullscreen mode
int marks = 45;

if(marks >= 50) {
    printf("Pass");
}
else {
    printf("Fail");
}
Enter fullscreen mode Exit fullscreen mode

else if statment


int marks = 75;

if(marks >= 90) {
    printf("Grade A");
}
else if(marks >= 75) {
    printf("Grade B");
}
else if(marks >= 50) {
    printf("Grade C");
}
else {
    printf("Fail");
}
Enter fullscreen mode Exit fullscreen mode

The switch statment

int day = 3;

switch(day) {
    case 1:
        printf("Monday");
        break;
    case 2:
        printf("Tuesday");
        break;
    case 3:
        printf("Wednesday");
        break;
    default:
        printf("Invalid day");
}
Enter fullscreen mode Exit fullscreen mode

When to use if condition

  • Checking ranges
  • using logical operators
  • complex codition

When to use switch condition

  • checking exact values
  • comparing one value

Top comments (0)