Kelvin Weather

For this project, how come my initial code doesn’t present the same result(same output) ?

My code:

//293 in Kelvin
const kelvin = 293;
kelvin - 273;
// convert Kelvin to Celsius
let celsius = kelvin;

output: 293

The correct code:

const kelvin = 293;
const celsius = kelvin-273;

output: 20

I feel like My Code should give me output 20. So why doesn’t it?

Any advice would be much appreciated!

That does not change the value of the variable kelvin.
If you wanted it to change, you’d have to do

let kelvin = 293;
kelvin = kelvin - 273;

I believe I understand what you mean, but if that is the case why is this acceptable?:
const celsius = kelvin-273;

If const Kelvin don’t change, then how can we subtract 273 from it and get 20? According to your answer it should remain 273.

That’s true. It doesn’t change the value of kelvin. When you initialize and declare the value celsius to the value of Kelvin - 273, that’s all it does. It says that celsius is equal to whatever kelvin is minus 273. We don’t want to change the value of kelvin, and we can’t (since it’s initialized using const instead of let/var).

To provide more value, your code isn’t working because “kelvin - 273” isn’t a valid JS expression. You have to either write what janbazant did, or if you only wanted to increment or decrement by 1, you could put “kelvin++” or “kelvin–”.

However, the logic of the task you’re trying to perform wouldn’t be reflected in the actual code you’re writing in that case, because to convert to celsius, we’re not trying to change Kelvin; we’re trying to derive what the temperature is in celsius from a temperature given in kelvin.

1 Like

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.