var, const or Let? Which to use?

Asked

Viewed 3,438 times

15

I recently discovered the existence of let and const but now I’m in doubt which one to use constantly?

And why I never see codes with let or const?

1 answer

21

Short version:

When should I wear:

  • var: never again
  • const: whenever possible
  • let: when the variable needs to be overwritten

Long version:

Ecmascript version 6 brought with it new commands to declare variables, the let and the const. This finally came to correct problems that the var had, and in practice we should not use more var. It’s still important to declare variables but now we have two options:

  • const

The const should be used in cases where the variable does not need to be reallocated, overwritten. This is most cases. The const blocks the variable to a constant value and will error if it is reallocated, it is as if in "read-only mode`, then:

const a = 10;
a = 20; // vai dar erro 

but it is worth noting that const obj = {} allows modifying the object, with for example obj.foo = 'bar' but does not allow to re-declare const obj = {novo: 'objeto'}.

  • let

The let is the new way of declaring variables that need to be overwritten. The most common case is an iteration of a loop, where the variable to iterate is overwritten N times during the loop.

Characteristics in common of let and const:

  • Both let and const do not allow a variable to be re-declared. This was allowed with var, without warnings being given, creating bugs that are difficult to detect.

  • Both declare the variable in the scope and bloco where they are, not allowing within the same function or block to re-declare the same variable.

These new versions are not yet used directly in browsers because the support is not yet universal, but are already used in environments pre-transpylated. The var is therefore advised against in new code.

  • This goes for Javascript and typescript?

  • @Luhhh yes, it is a matter of good practice to avoid errors. typescript helps minimize the problem, but the answer is still valid

Browser other questions tagged

You are not signed in. Login or sign up in order to post.