惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
Securelist
C
CERT Recently Published Vulnerability Notes
Forbes - Security
Forbes - Security
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
L
LINUX DO - 最新话题
The Hacker News
The Hacker News
Google Online Security Blog
Google Online Security Blog
SecWiki News
SecWiki News
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
The Last Watchdog
The Last Watchdog
S
Schneier on Security
T
Troy Hunt's Blog
N
News | PayPal Newsroom
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Schneier on Security
Schneier on Security
P
Privacy & Cybersecurity Law Blog
T
Tor Project blog
T
Threatpost
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
A
Arctic Wolf
S
Secure Thoughts
P
Proofpoint News Feed
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Security Latest
Security Latest
Scott Helme
Scott Helme
Security Archives - TechRepublic
Security Archives - TechRepublic
Latest news
Latest news
PCI Perspectives
PCI Perspectives
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Hacker News - Newest:
Hacker News - Newest: "LLM"
L
LINUX DO - 热门话题
P
Palo Alto Networks Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
G
GRAHAM CLULEY
V2EX - 技术
V2EX - 技术
Google DeepMind News
Google DeepMind News
Project Zero
Project Zero
V
Vulnerabilities – Threatpost
T
Threat Research - Cisco Blogs
Webroot Blog
Webroot Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
N
News and Events Feed by Topic
TaoSecurity Blog
TaoSecurity Blog
大猫的无限游戏
大猫的无限游戏
T
Tenable Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
V
Visual Studio Blog
H
Hacker News: Front Page
Simon Willison's Weblog
Simon Willison's Weblog
AWS News Blog
AWS News Blog

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback()
Don't Use JavaScript Variables Without Knowing Temporal Dead Zone
Dmitri Pavlutin · 2019-10-01 · via Dmitri Pavlutin Blog

Let me ask you a simple question. Which of the following code snippets will generate an error?

The first one that creates an instance, then defines the used class:


new Car('red'); // Does it work?

class Car {

constructor(color) {

this.color = color;

}

}


Or the second one that first invokes, then defines the function?


greet('World'); // Does it work?

function greet(who) {

return `Hello, ${who}!`;

}


The correct answer: the first snippet, the one with a class, generates a ReferenceError. The second works correctly.

If your answer is different than the above, or you made a guess without knowing what happens under the hood, then you need to grasp the Temporal Dead Zone (TDZ).

TDZ manages the availability of let, const, and class statements. It is important to how variables work in JavaScript.

1. What is Temporal Dead Zone

Let's start with a simple const variable declaration. If you first declare and initialize the variable, then access it, everything works as expected:


const white = '#FFFFFF';

white; // => '#FFFFFF'


Now let's try to access white variable before declaration:


white; // throws `ReferenceError`

const white = '#FFFFFF';

white;


In the lines of code until const white = '#FFFFFF' statement, the variable white is in Temporal Dead Zone.

Having white accessed in TDZ, JavaScript throws ReferenceError: Cannot access 'white' before initialization.

Temporal Dead Zone in JavaScript

Temporal Dead Zone semantics forbids accessing a variable before its declaration. It enforces the discipline: don't use anything before declaring it.

2. Statements affected by TDZ

Let's see the statements affected by TDZ.

2.1 const variables

As seen already, const variable is in TDZ before the declaration and initializtion line:


// Does not work!

pi; // throws `ReferenceError`

const pi = 3.14;


You have to use const variable after the declaration:


const pi = 3.14;

// Works!

pi; // => 3.14


2.2 let variables

let declaration statement is as well affected by TDZ until the declaration line:


// Does not work!

count; // throws `ReferenceError`

let count;

count = 10;


Again, use let variable only after the declaration:


let count;

// Works!

count; // => undefined

count = 10;

// Works!

count; // => 10


2.3 class statement

As seen in the introduction, you cannot use the class before defining it:


// Does not work!

const myNissan = new Car('red'); // throws `ReferenceError`

class Car {

constructor(color) {

this.color = color;

}

}


To make it work, keep the class usage after its definition:


class Car {

constructor(color) {

this.color = color;

}

}

// Works!

const myNissan = new Car('red');

myNissan.color; // => 'red'


2.4 super() inside constructor()

If you extend a parent class, before calling super() inside the constructor, this binding lays in TDZ:


class MuscleCar extends Car {

constructor(color, power) {

this.power = power;

super(color);

}

}

// Does not work!

const myCar = new MuscleCar('blue', '300HP'); // `ReferenceError`


Inside the constructor(), this cannot be used until super() is called.

TDZ suggests calling the parent constructor to initialize the instance. After doing that, the instance is ready, and you can make the adjustments in the child constructor.


class MuscleCar extends Car {

constructor(color, power) {

super(color);

this.power = power;

}

}

// Works!

const myCar = new MuscleCar('blue', '300HP');

myCar.power; // => '300HP'


2.5 Default function parameters

The default parameters exist within an intermidiate scope, separated from global and function scopes. The default parameters also follow the TDZ restriction:


const a = 2;

function square(a = a) {

return a * a;

}

// Does not work!

square(); // throws `ReferenceError`


The parameter a is used on the right side of the expression a = a, before being declared. This generates a reference error regarding a.

Make sure that the default parameter is used after its declaration and initialization. Let's use a special variable init that is initialized before usage:


const init = 2;

function square(a = init) {

return a * a;

}

// Works!

square(); // => 4


3. var, function, import statements

Contrary to the statements presented above, var and function definitions are not affected by TDZ. They are hoisted up in the current scope.

If you access var variable before the declaration, you simply get an undefined:


// Works, but don't do this!

value; // => undefined

var value;


However, a function can be used regarding where it is defined:


// Works!

greet('World'); // => 'Hello, World!'

function greet(who) {

return `Hello, ${who}!`;

}

// Works!

greet('Earth'); // => 'Hello, Earth!'


Often you're not interested much in the function implementation, rather you just want to call it. That's why sometimes it makes sense to invoke the function before defining it.

What's interesting that import modules are hoisted too:


// Works!

myFunction();

import { myFunction } from './myModule';


While import hoists, a good practice is to load module's dependencies at the beginning of the JavaScript file.

4. typeof behavior in TDZ

typeof operator is useful to determine whether a variable is defined within the current scope.

For example, the variable notDefined is not defined. Applying typeof operator on this variable does not throw an error:


typeof notDefined; // => 'undefined'


Because the variable is not defined, typeof notDefined evaluates to undefined.

But typeof operator has a different behavior when used with variables in a Temporal Dead Zone. In this case, JavaScript throws an error:


typeof variable; // throws `ReferenceError`

let variable;


The reason behind this reference error is that you can statically (just by looking at code) determine that variable is already defined.

5. TDZ acts within the current scope

The Temporal Dead Zone affects the variable within the limits of the scope where the declaration statement is present.

Limits of Temporal Dead Zone in JavaScript

Let's see an example:


function doSomething(someVal) {

// Function scope

typeof variable; // => undefined

if (someVal) {

// Inner block scope

typeof variable; // throws `ReferenceError`

let variable;

}

}

doSomething(true);


There are 2 scopes:

  1. The function scope
  2. The inner block scope where a let variable is defined

In the function scope, typeof variable simply evaluates to undefined. Here the TDZ of let variable statement has no effect.

In the inner scope the typeof variable statement, using a variable before the declaration, throws an error ReferenceError: Cannot access 'variable' before initialization. TDZ exists within this inner scope only.

6. Conclusion

TDZ is an important concept that affects the availability of const, let, and class statements. It doesn't allow to use the variable before the declaration.

Contrary, var variables inherit an older behavior when you can use the variable even before the declaration. You should avoid doing that.

In my opinion, TDZ is one of those good things when good coding practices reach into the language specification.