Do I need to use break or return?

Why doesn’t the solution in this exercise use:
break;

after each case statement?

If the case statements include a return, then break is unreachable and superfluous.

case 1:
  return a;
  break;    // not needed as it is unreachable
5 Likes

This gives the proper answer but also throws an undefined. When attempting to debug, it tells me that calculateWeight isn’t defined.

// Write your function here:
const calculateWeight = (earthWeight, planet) => {
	switch (planet) {
    case 'Murcury':
    	console.log(earthWeight * 0.378);
    	break;
    case 'Venus':
    	console.log(earthWeight * 0.907);
    	break;
    case 'Mars':
    	console.log(earthWeight * 0.377);
    	break;
    case 'Jupiter':
    	console.log(earthWeight * 2.36);
      break;
    case 'Saturn':
    	console.log(earthWeight * 0.916)
    	break;
    default:
    	console.log('Invalid Planet Entry. Try: Mercury, Venus, Mars, Jupiter, or Saturn.')
      break;
  }};

// 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!

The function logs an outcome then the above line logs the return value of the function, which is undefined. Suggest change all the lines in the switch to return a value rather than log it.

case 'Mercury':
    return earthWeight * 0.378;

Also, remove the break keyword from all cases.

2 Likes

This makes sense, using return and then removing the breaks. Taking your advice, it’s now returning only the answer, but still not passing the test.

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

Is there an error message given? Check your spelling of ‘Mercury’.

Apparently I just needed to reload. Same code, this time it passed. Thank you for the help!

1 Like