skip to Main Content
function convertToTemperature(degrees, unit) {
  if (unit === 'f') {
    const conversion = `${Math.round((degrees - 32) * 5/9)} C`;
    return conversion;
  } else if (unit === 'c') {
    const conversion = `${Math.round((degrees * 9/5) + 32)} F`;
    return conversion;
  }
  
  // This is the bold part referenced in the question
  else if (unit = '') {
    const conversion = `'${unit}' is not a valid measurement of Temperature`;
    return conversion;
  }
}
console.log(convertToTemperature(383, 'x'));

Because I’m using parameter ‘x’ when logging to the console I want it to log the string I’ve bolded. What is wrong in this section that isn’t running. I’m assuming it’s the "unit = ”" portion, I just don’t know what it should be equal to for all other values. I tried to leave it blank (else if{}) but that didn’t run either.

This function will output the correct code if I assign the parameter ‘unit’ a value of ‘f’ or ‘c’, but when I try to console.log ‘unit’ set to any other sting value it isn’t logging the intended string ('${unit}' is not a valid measurement of Temperature) and instead returns undefined. I’m a beginner so take it easy on me lol

2

Answers


  1. Since the last one covers everything besides f and c, you can just use an else.

    function convertToTemperature(degrees, unit) {
      if (unit === 'f') {
        const conversion = `${Math.round((degrees - 32) * 5/9)} C`;
        return conversion;
      } else if (unit === 'c') {
        const conversion = `${Math.round((degrees * 9/5) + 32)} F`;
        return conversion;
      } else {
        const conversion = `'${unit}' is not a valid measurement of Temperature`;
        return conversion;
      }
    }
    console.log(convertToTemperature(383, 'x'));

    Or if you want, you can also use a switch with the last as default

    function convertToTemperature(degrees, unit) {
      switch(unit){
          case "f": return `${Math.round((degrees - 32) * 5/9)} C`;
          case "c": return `${Math.round((degrees * 9/5) + 32)} F`;
          default: return `'${unit}' is not a valid measurement of Temperature`;
      }
    }
    console.log(convertToTemperature(383, 'x'));
    Login or Signup to reply.
  2. You could return early and for the last just return the unknown.

    function convertToTemperature(degrees, unit) {
        if (unit === 'f') return `${Math.round((degrees - 32) * 5/9)} C`;
        if (unit === 'c') return `${Math.round((degrees * 9/5) + 32)} F`;
        return `'${unit}' is not a valid measurement of Temperature`;
    }
    
    console.log(convertToTemperature(383, 'x'));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search