var, const or let? Which one to use?

12

Recently I discovered the existence of let and const but now I am in doubt which to use constantly?

And why do I never see codes with let or const ?

    
asked by anonymous 20.05.2017 / 07:59

1 answer

16

Short version:

When should I use:

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

Long version:

Version 6 of ECMAScript brought with it new commands to declare variables, let and const . This came to finally fix problems that var had, and in practice we should not use 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 reassigned, overwritten. This is the majority of cases. The const blocks the variable to a constant value and will give error if it is reassigned, it will look like that in read-only mode, then:

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

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

  • let

let is the new way to declare 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.

Common features 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 difficult to detect.

  • Both declare the variable in 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 support is not yet universal, but is already used in environments pre-transpilados . var is therefore advised against new code.

    
20.05.2017 / 09:13