Skip to main content

Command Palette

Search for a command to run...

Control Flow in JavaScript: If, Else, and Switch

Updated
3 min readView as Markdown
Control Flow in JavaScript: If, Else, and Switch

Everything is not availale for everyone.

Control Flow: The order in which code runs based on the conditions.
Instead of code run all line by line it has to ignore some lines through some coditions.

Use if conditions

let marks = 40

if(marks > 33){ // if with condtion of 33 value
    console.log('you are passed') // condtion true then run
}
// console.log (print) will only run if condtion match the values

Handle the other conditions

let marks = 40

if(marks > 33){ 
    console.log('you are passed')
} else {
    console.log('you are failed') //here is the others condition 
}
// In this code. console.log(print) statement will run. 

now we execute the condition with if and else one condition will run always

Lets add more conditions to discuss like

let marks = 40

if(marks > 33){ 
    console.log('you are passed')
if (marks > 90){ // add more condition with another values
    console.log('Got Grade A') 
if (marks > 75){ // add more condition with another values
    console.log('Got Grade B') 
} else {
    console.log('you are failed') 
}

runs code by checking conditions one by one and print the statement as per condition

Switch Statement

Used when you compare one value with many options

let day = 2;

switch (day) {            // difines variables 
  case 1:                 // case used for match the values 
    console.log("Monday");// if true then print 
    break;                // done and skip next (flow break)
  case 2:                     // previous not match 
    console.log("Tuesday");   // what need to be done
    break;                    // if match the end it
  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:                 // if none of condition matched 
    console.log("Invalid day");// run this code 
}

We can use Switch if we have multiple conditions with fixed values

When to use of if -else or switch

Use Case Best Choice
Checking ranges (age > 18) if-else
Multiple specific values switch
Complex logic if-else
Clean fixed options switch

Summary

if we have conditions to run the code then Control flows comes in the pictures

  • Use if → single condition

  • Use if-else → two paths

  • Use else if → multiple conditions

  • Use switch → many fixed values