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

推荐订阅源

D
DataBreaches.Net
S
Schneier on Security
T
The Exploit Database - CXSecurity.com
Webroot Blog
Webroot Blog
AI
AI
P
Palo Alto Networks Blog
Attack and Defense Labs
Attack and Defense Labs
WordPress大学
WordPress大学
月光博客
月光博客
阮一峰的网络日志
阮一峰的网络日志
Spread Privacy
Spread Privacy
T
Tor Project blog
罗磊的独立博客
小众软件
小众软件
S
Security Affairs
酷 壳 – CoolShell
酷 壳 – CoolShell
量子位
Apple Machine Learning Research
Apple Machine Learning Research
T
Threatpost
NISL@THU
NISL@THU
博客园_首页
PCI Perspectives
PCI Perspectives
大猫的无限游戏
大猫的无限游戏
IT之家
IT之家
N
News and Events Feed by Topic
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Forbes - Security
Forbes - Security
博客园 - 叶小钗
D
Darknet – Hacking Tools, Hacker News & Cyber Security
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Last Week in AI
Last Week in AI
L
LINUX DO - 热门话题
T
Threat Research - Cisco Blogs
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
腾讯CDC
Security Latest
Security Latest
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
The Cloudflare Blog
A
About on SuperTechFans
爱范儿
爱范儿
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
TaoSecurity Blog
TaoSecurity Blog
宝玉的分享
宝玉的分享
G
GRAHAM CLULEY
雷峰网
雷峰网
F
Full Disclosure
I
Intezer
Cloudbric
Cloudbric
博客园 - 三生石上(FineUI控件)
U
Unit 42

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()
JavaScript Variables Lifecycle: Why let Is Not Hoisted
Dmitri Pavlutin · 2016-07-27 · via Dmitri Pavlutin Blog

Hoisting is the process of virtually moving the variable or function definition to the beginning of the scope, usually for variable statement var and function declaration function fun() {...}.

When let (and also const and class, which have similar declaration behavior as let) declarations were introduced by ES2015, many developers including myself were using the hoisting definition to describe how variables are accessed. But after more search on the question, surprisingly for me hoisting is not the correct term to describe the initialization and availability of the let variables.

ES2015 provides a different and improved mechanism for let. It demands stricter variable declaration practices (you can't use before definition) and as result better code quality.

Let's dive into more details about this process.

1. Error prone var hoisting

Sometimes I see a weird practice of variables var varname and functions function funName() {...} declaration in any place in the scope:


// var hoisting

num; // => undefined

var num;

num = 10;

num; // => 10

// function hoisting

getPi; // => function getPi() {...}

getPi(); // => 3.14

function getPi() {

return 3.14;

}


The variable num is accessed before declaration var num, so it is evaluated to undefined. The function function getPi() {...} is defined at the end of file. However the function can be called before declaration getPi(), as it is hoisted to the top of the scope.

This is the classical hoisting.

As it turns out, the possibility to first use and then declare a variable or function creates confusion. Suppose you scroll a big file and suddenly see an undeclared variable... how the hell it does appear here and where is it defined?
Of course a practiced JavaScript developer won't code this way. But in the thousands of JavaScript GitHub repos is quite possible to deal with such code.

Even looking at the code sample presented above, it is difficult to understand the declaration flow in the code.

Naturally first you declare or describe an unknown term. And only later make phrases with it. let encourages you to follow this approach with variables.

2. Under the hood: variables lifecycle

When the engine works with variables, their lifecycle consists of the following phases:

  1. Declaration phase is registering a variable in the scope.
  2. Initialization phase is allocating memory and creating a binding for the variable in the scope. At this step the variable is automatically initialized with undefined.
  3. Assignment phase is assigning a value to the initialized variable.

A variable has unitialized state when it passed the declaration phase, yet didn't reach the initilization.

Variables lifecycle phases in JavaScript

Notice that in terms of variables lifecycle, declaration phase is a different term than generally speaking variable declaration. In simple words, the engine processes the variable declaration in 3 phases: declaration phase, initialization phase and assignment phase.

3. var variables lifecycle

Being familiar with lifecycle phases, let's use them to describe how the engine handles var variables.

var statement variables lifecycle

Suppose a scenario when JavaScript encounters a function scope with var variable statement inside. The variable passes the declaration phase and right away the initialization phase at the beginning of the scope, before any statements are executed (step 1). var variable statement position in the function scope does not influence the declaration and initialization phases.

After declaration and initialization, but before assignment phase, the variable has undefined value and can be used already.

On assignment phase variable = 'value' the variable receives its initial value (step 2).

Strictly hoisting consists in the idea that a variable is declared and initialized at the beginning of the function scope. There is no gap between declaration and initialization phases.
Let's study an example. The following code creates a function scope with a var statement inside:


function multiplyByTen(number) {

console.log(ten); // => undefined

var ten;

ten = 10;

console.log(ten); // => 10

return number * ten;

}

multiplyByTen(4); // => 40


When JavaScript starts executing multipleByTen(4) and enters the function scope, the variable ten passes declaration and initialization steps, before the first statement. So when calling console.log(ten) it is logged undefined.
The statement ten = 10 assigns an initial value. After assignment, the line console.log(ten) logs correctly 10 value.

4. Function declaration lifecycle

In case of a function declaration statement function funName() {...} it's even easier.

Function declaration variables lifecycle

The declaration, initialization and assignment phases happen at once at the beginning of the enclosing function scope (only one step). funName() can be invoked in any place of the scope, not depending on the declaration statement position (it can be even at the end).

The following code sample demonstrates the function hoisting:


function sumArray(array) {

return array.reduce(sum);

function sum(a, b) {

return a + b;

}

}

sumArray([5, 10, 8]); // => 23


When JavaScript executes sumArray([5, 10, 8]), it enters sumArray function scope. Inside this scope, immediately before any statement execution, sum passes all 3 phases: declaration, initialization and assignment.
This way array.reduce(sum) can use sum even before its declaration statement function sum(a, b) {...}.

5. let variables lifecycle

let variables are processed differently than var. The main distinction is that declaration and initialization phases are split.

let statement variables lifecycle

Now let's study a scenario when the interpreter enters a block scope that contains a let variable statement. Immediately the variable passes the declaration phase, registering its name in the scope (step 1).
Then interpreter continues parsing the block statements line by line.

If you try to access variable at this stage, JavaScript will throw ReferenceError: variable is not defined. It happens because the variable state is uninitialized.
variable is in the temporal dead zone.

When interpreter reaches the statement let variable, the initilization phase is passed (step 2). Now the variable state is initialized and accessing it evaluates to undefined. The variable exits the temporal dead zone.

Later when an assignment statement appears variable = 'value', the assignment phase is passed (step 3).

If JavaScript encounters let variable = 'value', then initialization and assignment happen in a single statement.

Let's follow an example. let variable number is created in a block scope:


let condition = true;

if (condition) {

// console.log(number); // => Throws ReferenceError

let number;

console.log(number); // => undefined

number = 5;

console.log(number); // => 5

}


When JavaScript enters if (condition) {...} block scope, number instantly passes the declaration phase.
Because number has unitialized state and is in a temporal dead zone, an attempt to access the variable throws ReferenceError: number is not defined. Later the statement let number makes the initialization. Now the variable can be accessed, but its value is undefined.
The assignment statement number = 5 of course makes the assignment phase.

const and class types have the same lifecycle as let, other than the assignment can happen only once.

5.1 Why hoisting is not valid in let lifecycle

As mentioned above, hoisting is variable's coupled declaration and initialization at the top of the scope. let lifecycle however decouples declaration and initialization phases. Decoupling vanishes the hoisting term for let.
The gap between the two phases creates the temporal dead zone, where the variable cannot be accessed.

In a sci-fi style, the collapsed hoisting in let lifecycle creates the temporal dead zone.

6. Conclusion

The freedom to declare variables using var is error prone.
Based on this lesson, ES2015 introduces let. It uses an improved algorithm to declare variables and additionally is block scoped.

Because the declaration and initialization phases are decoupled, hoisting is not valid for a let variable (including for const and class). Before initialization, the variable is in temporal dead zone and is not accessible.

To keep the variables declaration smooth, these tips are

  • Declare, initialize and then use variables. This flow is correct and easy to follow.
  • Keep the variables as hidden as possible. The less variables are exposed, the more modular your code becomes.

That's all for today. See you in my next post.

What do you think about variables coding best practices? Feel free to write a comment below!