In TypeScript, when do you use "let" and when do you use "const"?
As I meanwhile do almost exclusivey functional programming I find the destinction between const
and let
pretty useless.
I never ever reassign values to names. Never - regardless of the language.
Having said that I find the usage problematic due to 2 reasons.
const
is longer than let
(no seriously!)const
sort of communicates back: Hey! I am constant but that is not true (well it is, but ...) I had multiple times collegues that were totally surprised that this is possible
const x = { foo: "bar" }
x["foo"] = "Not bar!"
Sure the name and its reference is const but the object referenced is not. Granted in Typescript you can at least create
type ROO = Readonly<SomeType>
const x: ROO = someReferenceValue
x.someProp = "A wanna be a bar!" //compile error
So for Typescript const
finally could mean const
const
stands for constant
, and it means the variable cannot be reassigned at a later time.
let
is similar to var
except that it is block scoped, which means it can be declared inside of a for
loop and will be local to the body of that for
loop (and therefor does not exist outside of it)
The latter is different from a var
variable which can be declared anywhere but is always local to the function scope.
In general it is good practice to try and define your variables as const
as much as possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With