Welcome to “Deep Into The Essence” series, in which Blue will lead you to explore the essence behind the code, get a glimpse of the author’s thoughts and intentions behind the code, and experience the beauty of ingenious ideas and design beneath the essence

To understand why things are the way they are, put yourself in the shoes of the creator

– Blue

You may have heard that Blue doesn’t know what other people feel. The first feeling I saw was “who chose such a stupid name 😂”, which can’t be blamed on me, this name is almost the same type as” Big Dream, All things in one’s eyes “. This article will help you thoroughly understand the temporary dead zone and explore the principles behind it. Please like, favorites, comment and repost

In this article we will cover the following

  • Understand JavaScript variable declarations and scopes
  • What is a temporary dead zone
  • How different the temporary dead zones are for different variables
  • Get to the bottom of it: why did JS design TDZ mechanics and how does it work

Related articles

  • This article uses some of the previous undefined knowledge, if necessary welcome to check

    (link)

variable

Variables are the most basic and core feature of all languages. Even so, all other grammars exist for manipulating variables. After all, data is everything, everything is data

// The oldest variable declaration
var name='blue';

//ES6 adds two declarations
let url='www.zhinengshe.com';
const age=18;
Copy the code

There are three ways to declare

To better understand TDZ, let me briefly remind you of the differences between them:

Note that all three are easily compatible with all browsers through Babel, so compatibility is not a factor

  • var: the oldest traditional way to declare variablesIt has the most special mechanism, it will say below)
  • let: new in ES6 to prevent duplicate names, with block-level scope, with TDZ temporary dead zones
  • const: new in ES6, prevent the same name, with block-level scope, with TDZ temporary dead zone, constant cannot be modified

Just try it out

Var is the oldest and most common

var a=12;
var a=5;  // No error, var allows repeated declarations


if(true) {var b=44;
}
alert(b);  Var has no block-level scope.
Copy the code

Let does not allow repeated declarations and has block-level scope

let a=12;
let a=5; // An error is reported


if(true) {let b=44;
}
alert(b); B is a block-level variable and can only be used in if
Copy the code

Const is basically the same as let, except that it is constant

let a=12;
a=5; // Can be assigned again


const b=12;
b=5; // Error: constant, unmodifiable

const c; // Error: Constants cannot be modified, so they must have an initial value
Copy the code

scope

A scope represents one thing (variable, function, type, module…) The scope that can be used is limited to the scope of variables, after all, the others are similar

Three scopes

Js typically has three scopes:

  • Global scope: Declarations are in the outermost layer and can be used by any code
  • Local scope: declared in a function and used only in this function (and its children)
  • Block-level scope: a declaration (if, for, while, etc.) in a grammar block that can only be used within this grammar block

Just try it out

// Global variables -- declared outside all functions
var g1=12; // In non-strict mode, the global var is actually a window property
let g2=55;
const g3=23;


// Local variables are declared in functions
function show(){
  var l1='blue';
  let l2='zhangsan';
  const l3='lisi';
}
show();


// Block level variables
if(true) {var s1=18; Var has no block-level scope
  let s2=29;
  const s3=30;
}
console.log(s1); / / 18
console.log(s2); // an error was reported, s2 was not found
console.log(s3); // error: cannot find s3
Copy the code

What is a temporary dead zone and what is its essence

The temporary dead zone (𝓣𝓮𝓶𝓹𝓸𝓻𝓪𝓵 𝓓𝓮𝓪𝓭 𝓩𝓸𝓷𝓮) is a kind of… With this font is not the flavor of the 😂

What is the relationship between variables and scope and temporary dead zones? To put it simply, it is natural that variables should be declared first and then used. If I do not, Blue will be used before the declaration today. At this time, TDZ will be triggered to save the field

  • The period between the top of the scope and the actual declaration of the variable is called the dead zone
  • Because dead zones are temporary, they are called temporary dead zones when variables are declared

Let’s just look at an example

(() = >{
  // Scope starts
  
  
  /* This section is a dead zone, which means that a will die */
  
  
  //a true statement
  let a=12; }) ();Copy the code

So what happens if I use it?

(() = >{
  // Scope starts
  
  
  console.log(a);  // I will use it today
  
  
  //a true statement
  let a=12; }) ();Copy the code

All right… I was wrong

Variable specifies the area that is not allowed to be used

As you can see from the above example, variables are prohibited from being used before they are declared. If they are used, the program will die. This is a temporary dead zone, but is it really that simple

Question 1- Does var have TDZ

As we mentioned earlier, var does not have TDZ, so what happens if I use var in advance?

(function (){
  // Scope starts
  
  console.log(a); // not dead, just undefined
  
  // Actually declare variables
  var a=12; }) ();Copy the code

In other words, js before ES6 (i.e., var variable) will only get undefined if used in advance; ES6 starts (let and const) early, which directly raises a runtime error with a ReferenceError, but why? What the hell happened?

The nature of variable promotion

Js is an interpreted language, but there is also a pre-compilation stage in which js source code is compiled into JS bytecode (yes, it is similar to Java’s class bytecode mechanism). What does it do in the pre-compilation stage?

In the precompile phase, js scans all variables and allocates memory for them in advance. This process is called Variable promotion, or as of July 1, 1997, in layman’s terms. This is like bringing variables to the top of the scope

// Code in your eyes
function show(){
  console.log(a);
  
  var a=12;
  var b=5;
  
  console.log(b);
}



// Precompiled code
function show(){
  var a,b; // All variables are raised to the top of the scope. Of course, there are only declarations and no assignments. That's why they are undefined
  
  console.log(a); //undefined
  
  a=12;
  b=5;
  
  console.log(b); //5, because it's already assigned
}
Copy the code

The nature of TDZ temporary dead zones

Let and const are slightly different. They are also promoted. Instead of being initialized as undefined, they are marked as uninitialization. This state will now be removed (temporary dead zone)

// Code in your eyes
function show(){
  console.log(a);
  
  let a=12; // Unlike the previous example, we used let
  let b=5;
  
  console.log(b);
}



// Precompiled code
function show(){
  // Note that, for the sake of understanding, uninitialization is not used by JS, it only exists inside the engine
  let a=uninitialization,
      b=uninitialization;
  
  console.log(a); // Error due to uninitialization unavailable
  
  a=12;
  b=5;
  
  console.log(b); // This is ok because B went from uninitialization to 5
}
Copy the code

From this example, we see that a temporary dead zone is essentially a special state marked “not available”

Some of you might say, “Well, Sir, if I don’t give it a value, will it remain uninitialization?” And not

// Code in your eyes
function show(){
  console.log(a);
  
  let a;
  
  console.log(a);
}


// Precompiled code
function show(){
  let a=uninitialization;
  
  console.log(a);
  
  a=undefined; // Js automatically assigns undefined to any uninitialized variable
  
  console.log(a);
}
Copy the code

Question 2- What happens when you Pierce your shield with your spear?

Why do I feel like I’m being a little neutral while writing this article?

  • In the previous article, we mentioned a powerful thing called Typeof, which can be used with undefined variables without reporting an error
  • In this article, we talk about TDZ touch and die

So what if we use Typeof to process TDZ?

(() = >{
  / / start TDZ
  
  
  // Guess what?
  console.log(typeof a); // variables in TDZ
  console.log(typeof b); // There is no declared variable
  
  
  / / end of TDZ
  let a=12; }) ();Copy the code

So we also see that TDZ is higher than typeof, this is also normal, generally the new standard of things are higher than the old standard, or it will be shielded

Look at the essence: What exactly is TDZ and why does it exist

First of all, the issue has to do with JS itself, because JS is an interpreted language, that is, it doesn’t have a hard compile phase that other languages (like Java) don’t have at all

public class Test{
  static void main(String args[]){
    System.out.println(a);  // when a variable is used before a declaration

    int a=28; }}Copy the code

Brother, I was wrong.

A way to help

When JavaScript is precompiled, it is perfectly possible to initialize let, const, and var with undefined. This is simpler for the language itself. Why should it do this

  • Robustness considerations: First, we use it before variable declarations, right? Absolutely not, soundefinedToo soft. Take a stronger approach, help us figure this out
  • Easy to debug: As mentioned above, JS is supposed to help us find such silly errors so that we can debug our code easily, which is why even Typeof can’t be used in TDZ. Typeof is also a use, which is syntactically incorrect

A tool

As mentioned earlier, JS is an interpreted language, so it must promote variables during precompilation (otherwise it cannot check for errors such as duplicate declarations), so TDZ is not entirely for us developers. It can also help the compiler look for possible errors during compilation (duplicate declarations).

Var allows repeated declarations of this error, which was fixed with the help of TDZ as one of its contributions

When do YOU use TDZ?

As a user of the language, you will never actively use it, its value is to help you find problems (used before the announcement); For developers of the language itself, it can help with syntax problems such as duplicate declarations, but that’s about it, not much more

conclusion

It’s time to go over what Blue said, so first of all

  • The space from the top of the scope to where the variable is declared is the dead zone of the variable, so it’s called a temporary dead zone because it’s temporary
  • Variables are promoted to the top of the scope
  • varThe variable is promoted while the value is assignedundefined
  • letandconstMark it as uninitialization (TDZ state)
  • – TDZ variables should not be touched at all, they will die if touched (even typeof can’t do it)

Have a bug? Would like to add?

Thank you for watching this tutorial, if you have any questions or want to talk to me, please leave a comment directly. If you find anything inappropriate in this article, please also point out, thanks in advance