Let keyword: ES6 new enhanced version of the var keyword
Hello, today uncle would like to talk with you about the new keyword ES6 — let. Before we talk about the specific use of let, I want to tell you my own feelings about let. Let is actually an enhanced version of var. Why do you say that? Don’t worry. Just listen to what the uncle says.
First of all, let and var are used to declare variables in the same way. If you look at this, you might wonder, why do you need a new feature when it does the same thing?
To answer this question, let and VAR are different. For example, global variables declared by var are automatically added to top-level objects as properties, while let is not. For example, var allows declarations to be promoted or repeated, while LET does not. Of course, the differences don’t end there, and Uncle is just one example.
If you haven’t read about ES6 yet, this may be a bit confusing. Don’t take it to heart, because I’m going to talk to you about how to use let.
Declared global variables are not attributes of the top-level object
Before you understand the first difference between “let” and “var”, you need to talk about the use of the “var” keyword. Why is that? ! If you don’t understand var, then you want to understand let.
First of all, we know that a global variable can be declared with or without var. For example, this code looks like this:
var a = 'a'
console.log(a)
b = 'b'
console.log(b)
Copy the code
You don’t need to say much about this code, but you probably know what the results are — a and B. Don’t worry, this is just the beginning. We need to take it slow
Next, the uncle will delete the two above variables A and B with delete, and then print the values of the two variables respectively. Do you think the result that should be printed at this point is the statement? Yes! The value of variable A is normally output, but variable B is not defined. So why is that?
The uncle thinks you should know that the delete operator is used to delete properties of objects, but delete does not delete variables. Yes! You’re right. That means that a is a variable but not a property of the object, and B is a property of the object but not a variable.
Uncle said a little round, let me give you a scene. For example, if the above code is JavaScript code defined in an HTML page, then a is a global variable and B is an attribute of the window object. So, the delete operator can delete B, but not A.
The var keyword is used to declare variables and not to declare properties of the window object. Talking about here, uncle also have to SAO operation, let’s look at a code:
var a = 'a'
console.log(window.a)
var b = 'b'
console.log(window.b)
Copy the code
This code should print undefined and b if it follows the above conclusion. But if you actually run this code, you should know that it actually prints a and B!
How is this different from the above conclusion? ! Are you confused again? Don’t get blind. this problem is actually a minor mistake made by JavaScript author Brendan Eich when designing JavaScript: variables declared in a global scope are also added to top-level objects as properties.
May talk about here, you will be full screen of fun bullet screen: this hell who does not know? ! But that’s what I really want to talk to you about. This little mistake caused a global variable declared with the var keyword to pollute the global object.
ES6’s new LET fixes this problem nicely! That is, global variables declared using the let keyword do not pollute global objects. Var = let; var = let;
let a = 'a'
console.log(a)
console.log(window.a)
Copy the code
The actual result of this code is a and undefined. It turns out that let solves the var problem effectively, so you can see why ES6 added a keyword to do the same thing as var? !
Duplicate declarations are not allowed
But is let so slightly different from VAR? The answer is definitely not. Let’s continue with the var keyword. Variables declared using var are allowed to be declared repeatedly, as in this code:
var a = 'a'
var a = 'aa'
console.log(a)
Copy the code
This code eventually prints aa because var declares variables that are allowed to be declared repeatedly. Now you’re probably asking, “I know, what’s the problem?”
For example, if you define a JavaScript file that needs to be imported and used by other users, then the variables you declare in this file are redeclared in the same minute. How do you feel?
In a word, the naming of variables in real development must be planned and cannot be redeclared at will, which would make the namespace very messy.
You may be wondering, how do you solve this problem? The answer is simple: use the new LET keyword in ES6. Variables declared by the let keyword are not allowed to be declared twice, otherwise an error will be reported. Take a look at the following code:
let a = 'a'
let a = 'aa'
console.log(a)
Copy the code
SyntaxError: Identifier ‘a’ already been declared SyntaxError: Identifier ‘a’ has already been declared
So, you see, let is not just a little bit different.
Declarations are not allowed in advance
Are there any other differences between let and var? Uncle also do not hide the “yes”, simply one breath and you said it! Did you know that variables declared using the var keyword are allowed to be declared ahead of time? What? Don’t know! That’s ok. This is easy. Let’s look at this code:
console.log(a)
var a = 'a'
Copy the code
Why don’t you run this code and see what it prints? That’s right. Undefined. Why not report an error? The reason is that variables declared using the var keyword allow the declaration to be advanced. In human terms, the above code is essentially the same as the following:
var a
console.log(a)
a = 'a'
Copy the code
You may understand why the print result is undefined. However, we need to talk about let again, because the variable declared by let does not allow the declaration to be advanced. Here’s some code if you don’t believe me:
console.log(a)
let a = 'a'
Copy the code
ReferenceError: Cannot access ‘c’ before initialization ReferenceError: Cannot access ‘c’ before initialization
Temporary Dead Zones (TDZ)
Isn’t Let kind of cool? ! Do you want to know why the variables declared by let are not allowed to be declared earlier? This is because there is a concept called Temporal dead zone (TDZ) involved in using let to declare variables.
Doesn’t that sound a bit sophisticated? Ha ha ~ in fact, there is no deep, uncle to you figure out this thing. Same rules, let’s look at some code first:
if (true) {
console.log(a)
let a;
console.log(a)
a = "a";
console.log(a)
}
Copy the code
Uncle would like to ask you what are the three printed results in this code? You have to think about it carefully. This is what the uncle just told you.
- The first printed result is an error, the error message is
ReferenceError: Cannot access 'c' before initialization
- The second print is undefined
- The third print is a
You can probably understand the result, after all, it’s all just said. Now, you’ll have to pay close attention, because the uncle is here to talk to you about the concept of a temporary death zone.
A temporary dead zone means that variables declared using the let keyword are not initialized until the definition statement is executed. That is, the code is executed from the top until the variable is defined, and the variable cannot be accessed during this process, which is called a temporary dead zone.
In the case of the above code, the temporary dead zone actually begins and ends like this:
if (true) {
// Temporary dead zone begins
console.log(a); // ReferenceError: Cannot access 'a' before initialization
let a;
// The temporary dead zone is over
console.log(a); / / output is undefined
a = "a";
console.log(a); / / output a
}
Copy the code
At this point, The uncle believes you can understand what a temporary dead zone is. In fact, some new concepts are not difficult to understand, mainly the Angle and way you understand the problem.
typeof
Operators are no longer safe
In general, the let keyword is much stricter than the var keyword, resulting in fewer problems during development. But isn’t there anything wrong with let? The answer is obviously not, uncle has always believed that there is no optimal technology, only the most suitable.
The same is true of the let keyword in ES6, which, for example, has a problem with temporary dead zones. What’s the problem? You remember there’s an operator in JavaScript called typeof, which is used to determine the raw data type. This operator was relatively safe before let and, in other words, less error-prone. If you use it in a temporary dead zone, for example, it will report an error:
if (true) {
console.log(typeof c)
let c;
}
Copy the code
ReferenceError: Cannot access ‘c’ before initialization
Block-level scope
So far we have talked about let keyword, actually we are almost finished. However, let also has one of the most important features called block-level scope. Speaking of scopes, you probably know that in ES5 there are two: a global scope and a function scope, but in ES6 a block-level scope has been added.
Why do you need block-level scopes
To understand what block-level scopes are, we need to start with why we need block-level scopes. Same rules, but let’s look at some code:
var a = "a"
function fn() {
console.log(a)
if (false) {
var a = "b"
}
}
fn()
Copy the code
What do you think should be printed after this code is run? Is a? Is b? Or… . ? It turns out to be undefined. And, of course, it’s not that hard to figure out, you can just run it and see. The question is, why? !
Because ES5 has only global and function scopes, the result of this code is that local variables override global variables. Of course, there are more troubling problems, such as this code:
for (var i = 0; i < 5; i++) {
console.log("Inside the loop:" + i)
}
console.log("Out of circulation:" + i)
Copy the code
Is it incredibly familiar? ! It’s a for loop. What’s the point? The point is that after the for loop ends, you’ll still be able to access variable I. What does that mean? Stating that variable I is now a global variable. Of course, you might say there’s nothing wrong with that, because it hasn’t always been this way.
What is block-level scope
However, the uncle will tell you that now is different, now has the block level scope! What is block-level scope? Let’s start with some code:
if (true) {
let b = "b"
}
console.log(b)
Copy the code
SyntaxError: Lexical declaration cannot appear in a single-statement context
What does that mean? This means that the variables you declared with let are now not accessible in global scope, because variables declared with let have block-level scope.
So the next question you might ask is where is this block-level scope? The block-level scope is actually inside curly braces ({}). Let (); let (); let ();
for (let i = 0; i < 5; i++) {
console.log("Inside the loop:" + i)
}
console.log("Out of circulation:" + i)
Copy the code
After the transformation of this code after running the result is at the end of the loop after the print result is an error, error content uncle will not say, because all the same.
Considerations for block-level scopes
Now that you know what block-level scope is, it’s time to talk to you about what you need to be aware of. The let keyword must be used to declare block-scoped variables in the {} pair, otherwise the same error will be reported.
For example, we often omit {} when using if statements, but not when we use let declarations in if statements. Take a look at this code:
if (true) let c = 'c'
Copy the code
This code also results in an error, and the error content is the same. But don’t forget
The effects of block-level scopes
Ok, so what is a block-level scope, are you wondering what this block-level scope is for? Uncle miss you in the heart to face, hey hey ~
You know the anonymous autotuning function? Remember how to write an anonymous self-tuning function?
(function(){
var msg = 'this is IIFE.'
console.log(msg)
})()
Copy the code
Remember the function of anonymous self-tuning? To define variables and functions that don’t pollute the global namespace? ! With let and block-level scope, the above anonymous auto-tuning function can be written like this:
{
let msg = 'this is IIFE.'
console.log(msg)
}
Copy the code
Isn’t that a simplification? !
Write the last words
Ok, chat here, ES6 new let keyword all uncle want to talk with you about all finished, also hope to help you. Finally say a word: I do not want to mature uncle, for the front-end learning is no longer boring, difficult and confused efforts. Do you think this is a fun way to learn about front-end technology? What are your feelings, thoughts, and good suggestions