I am new to this forum so I hope that I am posting this question in the correct place?
I just completed Kelvin-Weather and have a question about the difference between “let” and “const”
The exercise tells us to use “const” for the Kelvin temperature and then “const” again for the Celsius temperature. Further down in the exercise they get us to calculate the temperature in Newtons but this time when I used “const” with Newton I got an error message:
/home/ccuser/workspace/learn-javascript-intro-kelvin-weather/app.js:17
newton = Math.floor(newton);
^
TypeError: Assignment to constant variable.
at Object. (/home/ccuser/workspace/learn-javascript-intro-kelvin-weather/app.js:17:8)
at Module._compile (module.js:571:32)
at Object.Module._extensions…js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:427:7)
at startup (bootstrap_node.js:151:9)
at bootstrap_node.js:542:3
When I changed “const newton = celsius *(33/100)” to “let newton = celsius *(33/100)” the code worked. I don’t understand why we could use const at the beginning of the exercise with Kelvin and Fahrenheit but that it had to change to “let” with Newton. I has something to do with the Math.floor command… I just don’t understand this.
The code is below:
const
is constant. The variable can never change. It’s an efficient way to declare something if you know it won’t change (it’ll help your program run smoother, especially scaled up… for an exercise it’s fine either way).
It also has the added benefit of not being accidently overriden. That being said it can’t be used without thought as to the nature of the data one is declaring.
Thanks for your quick reply. I think I understand that the Kelvin Temperature is the constant from which the other temperatures flow. Whatever the Kelvin Temperature entered, the other temperatures result from that. However, what I am having difficulty understanding is why I could use “const” for the Kelvin and Celsius temperature but then when the math.floor command was used to round of the subsequent temperatures, (fahrenheit and newton) that at that point I had to use the “let” variable instead. Can you explain how the math.floor command works and why this would affect the constant? Not sure if I am explaining myself very well.
Thanks
I think in this particular exercise they are rounding the number (the floor and ceiling operations round down and up to the nearest integer, respectively). Unless you create intermediate variables to hold the fractions you can’t use const all the way AND maintain round integer values. (It would be wasteful to create intermediate values just for the purpose of having their endpoints be const)
The topic of floating point numbers is explained very well here: Floating Point Numbers - Computerphile - YouTube
Thanks for the reply and the video.