Why will the let statement be very different from var?

I know let is to declare local variables of a block region, but why doesn't it support re-declaration and raising, like var ?

What is the design purpose of this restriction?

 (function(){ 'use strict'; alert(a); // undefined var a; })(); (function(){ 'use strict'; alert(a); // error let a; })(); (function(){ 'use strict'; var a; var a; alert(a); // undefined })(); (function(){ 'use strict'; let a; let a; // error alert(a); })(); 
+5
source share
2 answers

The idea is to create a tool that is more unique and rigorous than the original var .

As a human being, JavaScript is fair, but almost impossible to understand:

 alert(a); // Where does a come from? Why does this not throw? /* 1000 lines later, or even in an entirely different file */ var a; 

Also, imagine code with 5 var declarations for the same variable in the same scope, some of the if , some of for s. What is the first? What value will be created?

The idea was to fix some bad parts of var .

+8
source

For the same reason that any strict operator appears in any programming language - to limit the number of ways you can shoot yourself in the foot. The old school Javascript is just crowded with these.

Note that you can use let for the local-local area:

 while (i < 5) { let a = 42; i++; } 

Even if the loop is executed several times, a always initialized correctly.

Now, what happens if you have another variable in a higher scope?

 let a = 42; while (i < 5) { let a = 10; // What is the value of a here? i++; } // And here? 

There is a certain degree of ambiguity - and ambiguity is a bad feature in a programming language. This is not a problem with non-block var - it has tons of its own problems and people abuse it all the time, but at least it is obvious that var never blocked. And even then - people really use it as if it were blocky.

The only way to fix this madness is to make the language a little more rigorous. Does this actually mean that you have lost any feature? No. Variable shading was a bad idea with var , and it would still be a bad idea with let (and, as my example shows, maybe worse).

This is not unique to Javascript, not a long shot. For example, in C #:

 int i = 0; int i = 42; // Compiler error: A local variable named 'i' is already defined in this scope 

Why? Because you obviously made a mistake. Perhaps you copied a piece of code from another place and did not notice that you already have another variable named i . You may have forgotten that you are in the middle of another loop that also uses i as a loop variable. There is no real legal use, and yet there are tons of failures - this is just a terrible feature of the language. A simple compiler error prevents almost all of these crashes - and many of these crashes can be very difficult to find, especially if the "inner" block is not used too often.

+1
source

Source: https://habr.com/ru/post/1234170/


All Articles