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"?

+1
source share
2 answers

const means constant , and this means that the variable cannot be reassigned later.

let is similar to var , except that it is a block region, which means that it can be declared inside a for loop and will be local to the body of this for loop (and for this, do not exist outside of it)

The latter is different from the var variable, which can be declared anywhere, but always local to the function area.

In general, it is good practice to try to define your variables as const as much as possible.

+7
source

While I am doing almost exceptional functional programming, I find that the distinction between const and let pretty worthless. I never rewrite the meanings of names. Never - regardless of language.

Having said that, I find use problematic for two reasons.

  • const longer than let (not serious!)
  • const kind of communication: hey! I am permanent , but it’s not (it’s good, but ...) I had several colleagues who were completely surprised.

what is it possible

 const x = { foo: "bar" } x["foo"] = "Not bar!" 

Of course, the name and its link are const, but no link to the object is specified. Provided 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 can finally mean const

0
source

Source: https://habr.com/ru/post/1264302/


All Articles