In ECMA Script 6 you can define javascript variables with let and const , in addition to using var . What would be the recommendation to choose which type of variable definition should be used?
In ECMA Script 6 you can define javascript variables with let and const , in addition to using var . What would be the recommendation to choose which type of variable definition should be used?
To answer the question:
First, you must know each type of statement and clarify its scope within the javascript execution:
That is, example:
In the previous example it can be clearly seen how the variables
foo
andbar
can only be initialized, accessed and changed only within theclosure
but they cannot be accessed and/or changed outside of it...NOTE: in the previous example if you replace a
let
withvar
the same results will be obtained, I only put it as an example, a better example would be to say that a variablelet
defined inarchivo_1.js
could not be accessed inarchivo_2.js
while a variablevar
inarchivo_1.js
itself could be accessed and changed inarchivo_2.js
In addition, it should be clarified that type variables,
let
unlike type variables, CANNOT be accessed through the global object and cannot be re-declared , unlike type variables , for example:var
window
var
Namely:
When acting as type variables,
let
it must be taken into account that they cannot be accessed through the global objectwindow
, nor can they be re-declared and/or re-assigned with a new value.Finally and as a conclusion there would be some recommendations such as:
1. Use type variables
let
within functions , cycles and other code blocks whose execution is local, does not depend on other code and where said variables do not have to be accessed globally through the objectwindow
2. Use type variables
var
where said variable has to be accessed in other blocks of code and globally through the objectwindow
, that is:var jq = $;
3. Use CONSTANTS (
const
) for information such as an API KEY , a TOKEN , a value that ALWAYS HAS TO BE THE SAME, that is:const my_credit_card_number = 1234567890;
NOTE: only do the example above if you're in
nodejs
, hahaThe difference between
let
andvar
most important is scope (or scope). var will cause variables inside the nearest function to be defined. let will only be defined in the closest closed block. A part var declares the variables at the top of the closest function no matter where we declare it, which is known as hoisting ( +info ).let
it also does not allow us to create a variable with the same name, although it does allow it to be modified (unlikeconst
). Let's say itconst
has the same effect aslet
except that we can't modify the primitive value it stores. Yes, we could modify the properties of an object withconst
.Taking this into account, the use of one or the other depends on the functionality that you want to have in your program.