What is the difference between using LET instead of VAR in JavaScript? [duplicate]


As the question says, which is more optimal and why?:

let carro = "subaru";

var carro = "subaru"
asked by Victor Alvarado 19.06.2017 в 16:55

3 answers


let allows you to declare variables by limiting its scope to the block, declaration, or expression where it is being used. The above differentiates the let expression of the reserved word var, which defines a global or local variable in a function regardless of the scope of the block.

let vs var

When we use let within a block, we can limit the scope of the variable to that block. Note the difference a with var, whose scope resides within the function where the variable has been declared.

var a = 5;
var b = 10;

if (a === 5) {
  let a = 4; // El alcance es dentro del bloque if
  var b = 1; // El alcance es global

  console.log(a);  // 4
  console.log(b);  // 1

console.log(a); // 5
console.log(b); // 1

Source: Developer Mozilla

answered by 19.06.2017 в 17:00

let defines a local variable limiting its scope to the execution block, expression or declaration in which it is found. It is a non-standard feature so it can give problems in different browsers.

var defines a variable limiting its scope to the function in which it is defined or to the global scope (if it is not within a function), independently of the execution block in which it is executed.

  let variable_let = 'valor variable let';
  var variable_var = 'valor variable var';
  console.log('var dentro de bloque: ' + variable_var);
  console.log('let dentro de bloque: ' + variable_let);

console.log('var fuera de bloque: ' + variable_var);
console.log('let fuera de bloque: ' + variable_let);
answered by 19.06.2017 в 17:03

Several, but the most significant ones have to do with scope:

function cualquiera(){
  if (2 == 2){ // por poner algo
   var variable1 = 1
   let variable2 = 2
  // aqui variable1 existe
  // aqui variable2 no existe

The idea (IMHO) is to use var for private things in the module and let for things that are local in functions.

answered by 19.06.2017 в 17:00