2 votes

How to use the short circuit operators with the let variable?

It was something that happened to me using variables of type let, normally used by operators to short-circuit within a variable of type var axis:

var object1 = object1 || {};

but I found that if I attempt to perform the same operation with let the console it throws me :

Uncaught ReferenceError: object1 in not defined(...)

anyone know the reason or how to use this type of operators within the variables let, or to keep using var.

Postscript: the code editor webstorm it throws me that you should use let instead of var to prevent the lifting of variables or possible ship

2voto

Alvaro Montoro Points 38554

You're encountered with a problem that is explained in the page of MDN to let in the section "dead Zone temporary and errors with let", and that is due to the differences between let and var. In particular two of them:

  1. let does not allow the redeclaración of a variable with the same name in the same scope. Something that var yes that allows (basically shall be deemed to be an assignment, or will be ignored if it does not start the variable).

    It would throw an error of type TypeError. For example:

    let a = 1;
    let a = 2; // Error! el identificador ya se ha declarado
    
    let b = 1;
    var b = 2; // Error! el identificador ya se ha declarado
    
    var c = 1;
    var c = 2; // No problem, el valor de c será 2
    
  2. In ECMAScript 6, let does not increase the variable part supertior of the block. That means that you can't use the variable before declaring it, something you can do with var

    It would throw an error of type ReferenceError. For example:

    a = 1;      // Error! referencia a variable no definida
    let a = 2; 
    
    b = 1;      // No problem
    var b = 2;
    

Depending on the level at which you are performing the operation of short-circuit, it will give you an error or the other (in your case the second one), but basically the error is going to duty by one or the other. For example, when you:

let a = a || 1;

You're going to find with one of the following problems:

  • The variable a was already defined: syntax error, let does not allow you to redeclarar variables (1).
  • The variabla a was not defined: reference error, you're trying to use a on an assignment before it has been declared (2).

As you can see, the situation that is let is going to give you failure. That's why for the operator short-circuit you should use var in place.

HolaDevs.com

HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by:

X