01 / 05
Never changing? Use const
Some values are decided once and then left alone. A tax rate, pi, the name of the app — that sort of thing.
For those you use const instead of let.
const taxRate = 10;console.log(taxRate);Result
10
The basics of syntax
INPUT · Slides
01 / 05
Some values are decided once and then left alone. A tax rate, pi, the name of the app — that sort of thing.
For those you use const instead of let.
const taxRate = 10;console.log(taxRate);Result
10
02 / 05
Try to put a different value into a box you made with const and it stops with an error.
That sounds inconvenient, but it is there to stop you overwriting something by accident.
const name = "Yui";console.log(name);Result
Yui
03 / 05
When you are not sure, start with const. Move to let only when it turns out you need to change it.
const … not going to change (most of the time)let … going to change (counting, holding a state)Seeing "this will not change" written in the code is a comfort to whoever reads it.
const price = 300;let count = 0;count++;console.log(price * count);Result
300
04 / 05
The error you get for writing over a const is a slip being pointed out on the spot.
Had it been a let, something could quietly overwrite it and you would never know. The program would keep going, and the problem would surface much later as "the numbers do not add up".
The sooner it stops, the easier the cause is to find. That is what const is for.
05 / 05
For an important value that never changes anywhere in the program, there is a habit of writing the name entirely in capitals.
Write const MAX_COUNT = 100; and the reader knows this one is fixed on purpose.
It is a habit rather than a rule, but you will see it in other people's code, so it is worth knowing.
const TAX_RATE = 10;const price = 500;console.log(price + price / TAX_RATE);Result
550