Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In TypeScript, when do you use "let" and when do you use "const"?

In TypeScript, when do you use "let" and when do you use "const"?

like image 272
ortizjoe Avatar asked Aug 09 '16 19:08

ortizjoe


2 Answers

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

like image 65
robkuz Avatar answered Sep 28 '22 07:09

robkuz


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.

like image 23
vileRaisin Avatar answered Sep 28 '22 07:09

vileRaisin