0
0
Javascriptprogramming~5 mins

Switch vs if comparison in Javascript

Choose your learning style9 modes available
Introduction

We use switch and if to make decisions in code. They help the program choose what to do based on different conditions.

When you have many possible values for one variable and want to run different code for each.
When you want to check simple true/false conditions that are not just about one variable.
When you want clearer code for multiple choices instead of many if-else statements.
When you want to handle a few conditions quickly and simply.
When you want to compare the same variable against many values.
Syntax
Javascript
switch (expression) {
  case value1:
    // code to run if expression === value1
    break;
  case value2:
    // code to run if expression === value2
    break;
  default:
    // code to run if no case matches
}

// if statement
if (condition1) {
  // code if condition1 is true
} else if (condition2) {
  // code if condition2 is true
} else {
  // code if none of the above conditions are true
}

The switch compares one expression to many values.

The if can check any condition, not just equality.

Examples
This switch checks the value of day and prints a message.
Javascript
switch (day) {
  case 'Monday':
    console.log('Start of the week');
    break;
  case 'Friday':
    console.log('Almost weekend');
    break;
  default:
    console.log('Just another day');
}
This if checks ranges of score and prints the grade.
Javascript
if (score >= 90) {
  console.log('Grade A');
} else if (score >= 80) {
  console.log('Grade B');
} else {
  console.log('Grade C or below');
}
Multiple cases can run the same code in a switch.
Javascript
const color = 'red';
switch (color) {
  case 'red':
  case 'pink':
    console.log('Warm color');
    break;
  case 'blue':
    console.log('Cool color');
    break;
  default:
    console.log('Unknown color');
}
Sample Program

This program shows how switch and if can do the same thing: check the fruit and print its color.

Javascript
const fruit = 'apple';
switch (fruit) {
  case 'banana':
    console.log('Yellow fruit');
    break;
  case 'apple':
    console.log('Red or green fruit');
    break;
  case 'orange':
    console.log('Orange fruit');
    break;
  default:
    console.log('Unknown fruit');
}

if (fruit === 'banana') {
  console.log('Yellow fruit');
} else if (fruit === 'apple') {
  console.log('Red or green fruit');
} else if (fruit === 'orange') {
  console.log('Orange fruit');
} else {
  console.log('Unknown fruit');
}
OutputSuccess
Important Notes

Remember to use break in switch to stop running other cases.

if is more flexible for complex conditions.

switch is easier to read when checking one variable against many values.

Summary

switch is good for checking one value against many options.

if is better for complex or different conditions.

Both help your program decide what to do next.