When should I use if/else if/else statements? When should I use switch statements?

Question

When should I use if/else if/else statements? When should I use switch statements?

Answer

Consider using switch statements when you have more simple, albeit many cases/conditions, and/or your conditions to check are fixed values. Consider using if/else if/else statements when your logic requires more complex conditions to check and/or when the conditions to check will evaluate to a boolean.

2 Likes

switch perfectly works with the booleans as well

Yes. However, it is not considered good practise to write a switch statement like the following:

switch (true) {
  case expression < expression:
    // Code
    break;
  default:
    // Code
    break;
}

Eventhough it works, using ifelse ifelse statements will keep your code more readable and maintainable

5 Likes

I sometimes find it useful to combine switches with conditionals.

one of the code challenges was to calculate the weight of various planets depending on which one gets passed in as an argument.

const calculateWeight = ( earthWeight, planet ) => {
  planet = planet.toLowerCase();
  const planets = [ 'mercury', 'venus', 'mars', 'jupiter', 'saturn' ];

  if ( ! planets.includes( planet ) ){
    return 'Invalid Planet Entry. Try: Mercury, Venus, Mars, Jupiter, or Saturn.';
  } 
  else {
    switch ( planet ){
      case 'mercury':
        return (earthWeight * 0.378).toFixed(1);
        break;
      case 'venus':
        return (earthWeight * 0.907).toFixed(1);
        break;    
      case 'mars':
        return (earthWeight * 0.377).toFixed(1);
        break;
      case 'jupiter':
        return (earthWeight * 2.36).toFixed(1);
        break;
      case 'saturn':
        return (earthWeight * 0.916).toFixed(1);
        break;
      default: 
        return; 
        break;
    }    
  }
}
console.log( calculateWeight( 100, 'Jupiter' ) );
console.log( calculateWeight( 100, 'mercury' ) );
console.log( calculateWeight( 100, 'VeNuS' ) );
console.log( calculateWeight( 100, 'MARS' ) );
console.log( calculateWeight( 100, 'saturnnnnnnnnnn' ) );
10 Likes

Very cool! Thanks for sharing.

You don’t need to breaks after your returns in the switch statement, they will never be run as return will stop anymore code in the function running. Also your default does nothing, so may as well be omitted.

It is often argued that switch statements are bad, for example in this case polymorphism could solve the issue much nicer, each planet just needs a calculateWeight function. This is much easier to maintain and extend by adding new planets. Switch has a place, but it isn’t as wide spread as how much it is used.

2 Likes

The calculateWeight() exercise can be solved without the use of switch or if/else if blocks.
For example, the following solution using ternary operators…

function calculateWeight(earthWeight, planet) {
  // Perform validation first:
  if (
   Number.isNaN(earthWeight) || 
   typeof earthWeight !== 'number' || 
   typeof planet !== 'string'
  )
    return 'Invalid Argument. Provide valid Earth-weight(number) and Planet(string).';
  const validPlanets = ['Mercury', 'Venus', 'Mars', 'Jupiter', 'Saturn'];
  if (!validPlanets.includes(planet))
    return 'Invalid Planet Entry. Try: Mercury, Venus, Mars, Jupiter, or Saturn.';

  const g = planet === 'Mercury' ? 0.378
      : planet === 'Venus' ? 0.907
      : planet === 'Mars' ? 0.377
      : planet === 'Jupiter' ? 2.36
      : 0.916;
  return earthWeight * g;
}

…will yield the same results as this implementation (using switch):

function calculateWeight(earthWeight, planet) {
  if (
    Number.isNaN(earthWeight) ||
    typeof earthWeight !== 'number' || 
    typeof planet !== 'string'
  )
    return 'Invalid Argument. Provide valid Earth-weight(number) and Planet(string).';
  const validPlanets = ['Mercury', 'Venus', 'Mars', 'Jupiter', 'Saturn'];
  if (!validPlanets.includes(planet))
    return 'Invalid Planet Entry. Try: Mercury, Venus, Mars, Jupiter, or Saturn.';

  let g;
  switch (planet) {
    case 'Mercury':
      g = 0.378;
      break;
    case 'Venus':
      g = 0.907;
      break;
    case 'Mars':
      g = 0.377;
      break;
    case 'Jupiter':
      g = 2.36;
      break;
    default:
      g = 0.916;
  }
  return earthWeight * g;
}

…and this solution (using if/else if):

function calculateWeight(earthWeight, planet) {
  if (
    Number.isNaN(earthWeight) ||
    typeof earthWeight !== 'number' ||
    typeof planet !== 'string'
  )
    return 'Invalid Argument. Provide valid Earth-weight(number) and Planet(string).';
  const validPlanets = ['Mercury', 'Venus', 'Mars', 'Jupiter', 'Saturn'];
  if (!validPlanets.includes(planet))
    return 'Invalid Planet Entry. Try: Mercury, Venus, Mars, Jupiter, or Saturn.';

  let g;
  if (planet === 'Mercury') {
    g = 0.378;
  } else if (planet === 'Venus') {
    g = 0.907;
  } else if (planet === 'Mars') {
    g = 0.377;
  } else if (planet === 'Jupiter') {
    g = 2.36;
  } else {
    g = 0.916;
  }
  return earthWeight * g;
}

1 Like

My solution was:

const calculateWeight = (earthWeight, planet) => {

  switch (planet) {
    case 'Mercury':
    return (earthWeight * 0.378);
    break;
    case 'Venus':
    return (earthWeight * 0.907);
    break;
    case 'Mars':
    return (earthWeight * 0.377);
    break;
    case 'Jupiter':
    return (earthWeight * 2.36);
    break;
    case 'Saturn':
    return (earthWeight * 0.916);
    break;
    default:
    return 'Invalid Planet Entry. Try: Mercury, Venus, Mars, Jupiter, or Saturn.';
  }
}

console.log(calculateWeight(100, 'Jupiter')) // Should print 236
6 Likes

I find this solution cleaner:
function calculateWeight(earthWeight, planet) {
let weight;
if(planet === ‘Mercury’) {
weight = earthWeight * 0.378
return ${weight}
}if(planet === ‘Venus’) {
weight = earthWeight * 0.907
return ${weight}
}if(planet === ‘Mars’) {
weight = earthWeight * 0.377
return ${weight}
}if(planet === ‘Jupiter’) {
weight = earthWeight * 2.36
return ${weight}
}if(planet === ‘Saturn’) {
weight = earthWeight * 0.916
return ${weight}
} else {
return ‘Invalid Planet Entry. Try: Mercury, Venus, Mars, Jupiter, or Saturn.’
}
}
And it works too!

1 Like

Anybody knows what’s wrong with this solution? The code works but I don’t get a check.

// Write your function here:

const calculateWeight = (earthWeight, planet) => {
  if (planet === 'Mercury') {
    return earthweight * .378;
  } else if (planet === 'Venus') {
    return earthWeight * .907;
  } else if (planet === 'Mars') {
    return earthWeight * .377;
  } else if (planet === 'Jupiter') {
    return earthWeight * 2.36;
  } else if (planet === 'Saturn') {
    return earthWeight * .916;
  } else {
    return 'Invalid Planet Entry. Try: Mercury, Venus, Mars, Jupiter, or Saturn.';
  }
}

// Uncomment the line below when you're ready to try out your function
console.log(calculateWeight(100, 'Jupiter')) // Should print 236

// We encourage you to add more function calls of your own to test your code!```

Looks good and works fine! It looks to me like my solution is just in a case break format, so I really don’t get why my solution is not accepted.

I can see there’s a variable “earthWeight” (capital w for weight) and then “earthweight” is used on line 3. Could this be why?

2 Likes

const calculateWeight = (earthWeight, planet) => {

earthWeight = 100;

switch (planet) {
    case 'Mercury':
        return (.378 * earthWeight);
    case 'Venus':
        return (.907 * earthWeight);
    case 'Mars':
        return (.377 * earthWeight);
    case 'Jupiter':
        return (2.36 * earthWeight);
    case 'Saturn':
        return (.916 * earthWeight);
    default:
        return 'Invalid Planet Entry. Try: Mercury, Venus, Mars, Jupiter, or Saturn.';
}

};

What I really like from your code is the → planet = planet.toLowerCase(); I think that is a great addition that I didn’t include in mine.

4 Likes

// use if / else if / else statements

const calculateWeight = (earthWeight, planet) => {
if (planet === ‘Mercury’){
return earthWeight * 0.378;
} else if (planet === ‘Venus’){
return earthWeight * 0.907;
} else if (planet === ‘Mars’){
return earthWeight * 0.377;
}
else if (planet === ‘Jupiter’){
return earthWeight * 2.36;
}
else if (planet === ‘Saturn’){
return earthWeight * 0.916;
} else {
return ‘Invalid Planet Entry. Try: Mercury, Venus, Mars, Jupiter, or Saturn.’
}
}

//use switch statements
const calculateWeight = (earthWeight, planet) => {
switch(planet){
case ‘Mercury’:
return earthWeight * 0.378;
break;
case ‘Venus’:
return earthWeight * 0.907;
break;
case ‘Mars’:
return earthWeight * 0.377;
break;
case ‘Jupiter’:
return earthWeight * 2.36;
break;
case ‘Saturn’:
return earthWeight * 0.916;
break;
default:
return ‘Invalid Planet Entry. Try: Mercury, Venus, Mars, Jupiter, or Saturn.’
break;
}
}

The code isnt good,why?
You dont continue all from you switch statement, like you not defined default, so you switch statement isnt complete, you use If, and that isnt good if you have default and you default is empty, and other you used const planets array, where in the task was strictly say what you choiced, and if you miss the planets of vote, that you default statement will work.
So is not good you code :confused:
Its look realy pretty but as I writing :slight_smile:

calculateWeight = (earthWeight, planet) => {
switch (planet) {
case “Mercury”:
return earthWeight * 0.378;
case “Venus”:
return earthWeight * 0.907;
case “Mars”:
return earthWeight * 0.377;
case “Jupiter”:
return earthWeight * 2.36;
case “Saturn”:
return earthWeight * 0.916;
default:
return “Invalid Planet Entry. Try: Mercury, Venus, Mars, Jupiter, or Saturn.”;
}
};
console.log(calculateWeight(100, “Mercury”));

yes, like you say, I aggre

This is Impressive, but why use this when a simpler version like the one below could still get the job done and make the script run faster;

const calculateWeight = (earthWeight, planet) => {
  planet = planet.toLowerCase();
  if (planet === "Mercury"){
    weight = earthWeight * 0.378;
    return weight;
  } else if (planet === "Venus"){
    weight = earthWeight * 0.907;
    return weight
  } else if (planet === "Mars"){
    weight = earthWeight * 0.377;
    return weight;
  } else if (planet === "Jupiter"){
    weight = earthWeight * 2.36;
    return weight;
  } else if (planet === "Saturn"){
    weight = earthWeight * 0.916;
    return weight;
  } else {
    return 'Invalid Planet Entry. Try: Mercury, Venus, Mars, Jupiter, or Saturn.'
  } 
  
}



I guess using switch is also simple and takes less coding.

const calculateWeight = (earthWeight, planet) => {
  planet = planet.toLowerCase();
switch (planet) {
  case 'mercury':
  return earthWeight * 0.378;
  case 'venus':
  return earthWeight * 0.907;
  case 'mars':
  return earthWeight * 0.377;
  case 'jupiter':
  return earthWeight * 2.36;
  case 'saturn':
  return earthWeight * 0.916; 
  default:
  return 'Invalid Planet Entry. Try: Mercury, Venus, Mars, Jupiter, or Saturn.'
  }
}
1 Like

That’s pretty much what I used for mine. I also wrapped this all in an if/else statement to make sure the earthWeight entered is a number.

const calculateWeight = (earthWeight, planet) => {
  planet = planet.toLowerCase();
  if (typeof earthWeight === 'number') {
    switch (planet) {
      case 'mercury':
      return earthWeight * 0.378;
      case 'venus':
      return earthWeight * 0.907;
      case 'mars':
      return earthWeight * 0.377;
      case 'jupiter':
      return earthWeight * 2.36;
      case 'saturn':
      return earthWeight * 0.916; 
      default:
      return 'Invalid Planet Entry. Try: Mercury, Venus, Mars, Jupiter, or Saturn.'
    }
  } else {
    return 'Invalid Number Entry';
  }
};