I am trying to create a function that converts celcius to fahrenheit and vice versa using a return statement inside. I’m confused why the code below won’t return or log anything on the console but the bottom bit of code will.
function convertTemp2(degrees,unit) {
if (unit === 'F' || unit === 'C') {
conversion(degrees,unit);
console.log(`${degrees} ${unit}`)
} else {
console.log('please use C for celcius, and F for fahrenheit');
}
}
function conversion(degrees,unit) {
if (unit === 'F') {
degrees = (degrees+32) *5/9;
unit = 'C';
return degrees, unit;
} else if (unit === 'C') {
degrees = (degrees*9/5) + 32;
unit = 'F';
return degrees, unit;
}
}
convertTemp2(1023,'F');
convertTemp2(12,'C');
convertTemp2(123,'H');
This seems to work:
function convertTemp2(degrees,unit) {
if (unit === 'F' || unit === 'C') {
conversion(degrees,unit);
} else {
console.log('please use C for celcius, and F for fahrenheit');
}
}
function conversion(degrees,unit) {
if (unit === 'F') {
degrees = (degrees+32) *5/9;
console.log(`${degrees}C`)
} else if (unit === 'C') {
degrees = (degrees*9/5) + 32;
console.log(`${degrees}F`)
}
}
convertTemp2(1023,'F');
convertTemp2(12,'C');
convertTemp2(123,'H');
2
Answers
it should look like
The issue in your first code snippet lies in the way you’re using the
return
statement in your conversion function.In JavaScript, the return statement can only return a single value.
When you write
return degrees, unit;
, it doesn’t actually return bothdegrees
andunit
as separate values.Instead, it evaluates
degrees, unit
as an expression and returns only the value ofunit
.To fix this issue, you could modify your
conversion
function to return an object containing bothdegrees
andunit
:And then, in your
convertTemp2
function, you can extract the values from the returned object and use them:You can preserve both values and use them correctly in your
convertTemp2
function.And for your second code snippet it works because it directly logs the converted temperature and unit within the conversion function, without the need for returning any values.