”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 通过 ECMAScript 标准的棱镜了解 var、let 和 const 之间的差异。

通过 ECMAScript 标准的棱镜了解 var、let 和 const 之间的差异。

发布于2024-08-29
浏览:826

The Differences Between var, let, and const Through the Prism of the ECMAScript Standard.

Many articles explain the differences between var, let, and const using terms such as hoisting, Temporal Dead Zone(TDZ), functional and block scope, etc., often without referencing the standard. Some of those terms are not even included in the language standard. It's perfectly fine to explain the topic without referencing the language standard. However, I explain the topic by referencing it for those who want to dig a bit deeper, as understanding the ECMAScript standard is crucial for a comprehensive grasp of JavaScript.

ECMAScript

Many organisations have their references for JavaScript, such as MDN Web Docs, javascript.info, and others. However, there is one standards organisation whose sole purpose is to standardise and document computer systems. This organisation is Ecma International, a reliable authority in the field. The organisation maintains a standard called ECMA-262, a company's internal number to identify the standard. Ecma International defines this standard as the backbone of the ECMAScript general-purpose programming language, which we commonly call JavaScript. Understanding this standard is key to understanding the language itself. The latest standard as of August 2024 is the 15th edition of ECMAScript, also known as ECMAScript 2024.

Execution Context

To understand the differences between var, let, and const, it's essential to understand the concept of Execution Context.

Execution Context is an abstract structure defined in the ECMAScript standard. It is the environment where the current code is executed. To simplify things, we can assume a Global Execution Context and a Functional Execution Context exist.

// Global Execution Context
let globalVariable = 'This is a global variable'

function outerFunction() {
  // Outer Function Execution Context
  let outerVariable = 'This is an outer variable'

  function innerFunction() {
    // Inner Function Execution Context
    let innerVariable = 'This is an inner variable'
  }

  innerFunction()
}

outerFunction()

To track the code's execution, Execution Context includes several components, known as state components. Among these, the LexicalEnvironment and VariableEnvironment are crucial when understanding the behaviour of var, let, and const keywords.

Both LexicalEnvironment and VariableEnvironment are Environment Records. Environment Record is also an abstract data structure defined in the ECMAScript standard. It establishes the association of Identifiers to specific variables and functions. An Identifier is a name that references values, functions, classes and other data structures in JavaScript. In the following example, let variable = 42, variable is the variable's name (Identifier) that stores the value of the number 42.

Every time code is executed, the Execution Context creates a new Environment Record. Besides storing Identifiers Environment Record has an [[OuterEnv]] field, either null or a reference to an outer Environment Record.

Graphically, Execution Context and Environment Record from the previous example could be represented like this:

// Global Execution Context
{
  // Environment Record
  {
    identifier: 'globalVariable'
    value: 'This is a global variable'
  }
  {
    identifier: 'outerFunction'
    value: Function
  }
  [[OuterEnv]]: null
}

// Outer Function Execution Context
{
  // Environment Record
  {
    identifier: 'outerVariable'
    value: 'This is an outer variable'
  }
  {
    identifier: 'innerFunction'
    value: Function
  }
  [[OuterEnv]]: Global Execution Context
}


// Inner Function Execution Context
{
  // Environment Record
  {
    identifier: 'innerVariable'
    value: 'This is an inner variable'
  }
  [[OuterEnv]]: Outer Function Execution Context
}

Another important point to remember about the Execution Context is that it has two distinct phases: the Creation Phase and the Execution Phase. These two phases are vital in understanding the difference between var and let or const.

Let and Const Declarations

In the paragraph 14.3.1 Let and Const Declarations of ECMAScript standard the following is stated:

let and const declarations define variables that are scoped to the running execution context's LexicalEnvironment. The variables are created when their containing Environment Record is instantiated but may not be accessed in any way until the variable's LexicalBinding is evaluated. A variable defined by a LexicalBinding with an Initializer is assigned the value of its Initializer's AssignmentExpression when the LexicalBinding is evaluated, not when the variable is created. If a LexicalBinding in a let declaration does not have an Initializer the variable is assigned the value undefined when the LexicalBinding is evaluated.

To understand this statement, I will explain it sentence by sentence.

let and const declarations define variables that are scoped to the running execution context's LexicalEnvironment.

It means variables created with the let or const keywords are scoped to the block where they were defined. The code block is any JavaScript code inside the curly braces.

let condition = true
if (condition) {
  let blockScopedVariable = 'This is a block-scoped variable'
  console.log(blockScopedVariable) // This is a block-scoped variable
}

console.log(blockScopedVariable) // ReferenceError: blockScopedVariable is not defined

// Global Execution Context
{
  // Environment Record
  {
    identifier: 'condition'
    value: true
  }
  [[OuterEnv]]: null
  // Block Environment Record
  {
    identifier: 'variable'
    value: 'This is a block-scoped variable'
  }
  [[OuterEnv]]: Global Execution Context 
}

The variables are created when their containing Environment Record is instantiated but may not be accessed in any way until the variable's LexicalBinding is evaluated.

As previously mentioned, the Execution Context has two phases. This statement means that during the Creation Phase of the Execution Context, variables are stored in their corresponding Environment Record but have not yet been assigned any value. They are uninitialised.

console.log(varaible) // ReferenceError: Cannot access 'varaible' before initialization

let varaible = 42

// Global Execution Context Creation Phase
{
  // Environment Record
  {
    identifier: 'variable'
    value: uninitialised
  }
  [[OuterEnv]]: null
}

Because the variable is already created (instantiated) in the Environment Record, the Execution Context knows about it but can't access it before evaluation(the Execution Phase of the Execution context). The state of the variable being uninitialised is also known as a Temporary Dead Zone(TDZ). We would have a different error if the variable hadn't been created in the Environment Record.

console.log(varaible) // ReferenceError: varaible is not defined

// Global Execution Context Creation Phase
{
  // Environment Record
  {
  }
  [[OuterEnv]]: null
}

A variable defined by a LexicalBinding with an Initializer is assigned the value of its Initializer's AssignmentExpression when the LexicalBinding is evaluated, not when the variable is created.

LexicalBinding is a form of the Identifier, which represents the variable's name. The Initializer is the variable's value, and AssignmentExpression is the expression used to assign that value to the variable's name, such as the '=' sign in let variable = 42. Therefore, the statement above means that variables created with let or const keywords are assigned their value during the Execution Phase of the Execution Context.

let variable = 42

// Global Execution Context Creation Phase
{
  // Environment Record
  {
    identifier: 'variable'
    value: uninitialised
  }
  [[OuterEnv]]: null
}

// Global Execution Context Execution Phase
{
  // Environment Record
  {
    identifier: 'variable'
    value: 42
  }
  [[OuterEnv]]: null
}

If a LexicalBinding in a let declaration does not have an Initializer the variable is assigned the value undefined when the LexicalBinding is evaluated.

This means that if a let variable is created without an initial value, undefined is assigned to it during the Execution Phase of the Execution Context. Variables declared with the const keyword behave differently. I will explain it in a few paragraphs later.

let variable
// Global Execution Context Creation Phase
{
  // Environment Record
  {
    identifier: 'variable'
    value: uninitialised
  }
  [[OuterEnv]]: null
}

// Global Execution Context Execution Phase
{
  // Environment Record
  {
    identifier: 'variable'
    value: undefined
  }
  [[OuterEnv]]: null
}

The standard also defines a subsection called 14.3.1.1 'Static Semantics: Early Errors,' which explains other essential aspects of variables defined with the let and const keywords.

LexicalDeclaration: LetOrConst BindingList;

  • It is a Syntax Error if the BoundNames of BindingList contains "let".
  • It is a Syntax Error if the BoundNames of BindingList contains any duplicate entries. LexicalBinding : BindingIdentifier Initializer
  • It is a Syntax Error if Initializer is not present and IsConstantDeclaration of the LexicalDeclaration containing this LexicalBinding is true.

LetOrConst is a grammar rule which specifies that variable declarations can start with the let or const keywords.
BindingList is a list of variables declared with let or const keywords. We could imagine BindingList as a data structure like this:

let a = 1
let b = 2
let c = 3
const d = 4
const e = 5

BindingList: [
    { 
        identifier: 'a',
        value: 1
    },
    { 
        identifier: 'b',
        value: 2
    },
    { 
        identifier: 'c',
        value: 3
    },
    { 
        identifier: 'd',
        value: 4
    },
    { 
        identifier: 'e',
        value: 5
    }
]

A Syntax Error is an error that breaks the language's grammatical rules. They occur before the code's execution. Let's analyse the first Syntax Error.

  • It is a Syntax Error if the BoundNames of BindingList contains "let".

The BoundNames of BindingList are the names of variables declared with let or const keywords.

let a = 1
let b = 2
let c = 3
const d = 4
const e = 5

BoundNames: ['a', 'b', 'c', 'd', 'e']

A Syntax Error will occur when the BoundNames list contains “let”.

let let = 1 // SyntaxError: let is disallowed as a lexically bound name
const let = 1 // SyntaxError: let is disallowed as a lexically bound name
  • It is a Syntax Error if the BoundNames of BindingList contains any duplicate entries.

It means we can't use the same names for variables declared with the let or const keywords if they are already used in that scope.

let a = 1
let a = 2 // SyntaxError: Identifier 'a' has already been declared
  • It is a Syntax Error if Initializer is not present and IsConstantDeclaration of the LexicalDeclaration containing this LexicalBinding is true.

IsConstantDeclaration is an abstract operation in the standard that checks if the variable is declared with the const keyword. This rule could be decrypted like that: if IsConstantDeclaration is true and the variable doesn't have an Initializer, a Syntax Error will be returned.

const x; // SyntaxError: Missing initializer in const declaration

Another vital thing only related to the const keyword: variables declared with the const keyword can't be reassigned. It is not stated explicitly in the standard, but we can get it from the IsConstantDeclaration operation and the syntax rule that variables declared with the const keyword should always be initialised with the Initializer

const variable = 42
variable = 46 // TypeError: Assignment to constant variable

Variable Statement

Before 2015, when the ECMAScript 2015 wasn't released yet, only the var keyword was available to create a variable in JavaScript.

In the paragraph 14.3.2 Variable Statement of ECMAScript standard the following is stated:

A var statement declares variables scoped to the running execution context's VariableEnvironment. Var variables are created when their containing Environment Record is instantiated and are initialized to undefined when created. Within the scope of any VariableEnvironment a common BindingIdentifier may appear in more than one VariableDeclaration but those declarations collectively define only one variable. A variable defined by a VariableDeclaration with an Initializer is assigned the value of its Initializer's AssignmentExpression when the VariableDeclaration is executed, not when the variable is created.

I again explain it sentence by sentence.

A var statement declares variables scoped to the running execution context's VariableEnvironment.

This means that variables declared with the var keyword are either function-scoped if declared inside a function or global-scoped if declared outside any function.

let condition = true
if (condition) {
    var globalVariable = 'This is a global variable'
}

console.log(globalVariable ) // This is a global variable

function outerFunction() {
  // Outer Function Execution Context
  var outerVariable = 'This is an outer variable'
}

outerFunction()

// Global Execution Context
{
  // Environment Record
  {
    identifier: 'condition'
    value: true
  }
  {
    identifier: 'globalVariable'
    value: 'This is a global variable'
  }
  {
    identifier: 'outerFunction'
    value: Function
  }
  [[OuterEnv]]: null
}

// Outer Function Execution Context
{
  // Environment Record
  {
    identifier: 'outerVariable'
    value: 'This is an outer variable'
  }
  [[OuterEnv]]: Global Execution Context
}

Var variables are created when their containing Environment Record is instantiated and are initialized to undefined when created.

During the Creation Phase of the Execution Context variables are assigned the undefined value. The process of assigning the undefined to a variable during the Creation Phase is often referred to as "hoisting" or declaration hoisting. It is worth mentioning that the terms "hoisting" or declaration hoisting are not included in the standard. However, it is a convention used by many developers to explain the availability of variables "before" they were declared.

console.log(globalVariable) // undefined

var globalVariable = 'This is a global variable'

// Global Execution Context Creation Phase
{
  // Environment Record
  {
    identifier: 'globalVariable'
    value: undefined
  }
  [[OuterEnv]]: null
}

Sometimes, it is explained that the code example above is possible because variables declared with the var keyword are "moved" to the top of the scope. However, nothing is moved anywhere; it is only possible by assigning the undefined value to the variable during the Creation Phase of Execution Context.

Within the scope of any VariableEnvironment a common BindingIdentifier may appear in more than one VariableDeclaration but those declarations collectively define only one variable.

BindingIdentifier is a more specific type of the Identifier. We used the Identifier term before to explain the name of a variable. While Identifier also refers to the variable's name, BindingIdentifier is only used in the context of the declaration of variables (function or other data structure).

let variable = 42 // BindingIdentifier
console.log(variable )  // Identifier

Now, let's go back to explaining the sentence's meaning.

BindingIdentifier may appear in more than one VariableDeclaration

In the same scope, we can create multiple variables with the same name using the var keyword, whilst all these "variables" reference only one variable.

var variable = 42
var variable = 66
var variable = 2015

// Execution context
{
    // Environment Record
    {
        identifier: 'variable '
        value: 2015
    }
    [[OuterEnv]]: null
}

It may appear we declared three variables with the BindingIdentifier variable, but we just reassigned the original variable variable twice. First, we reassigned it from 42 to 66, then from 66 to 2015

A variable defined by a VariableDeclaration with an Initializer is assigned the value of its Initializer's AssignmentExpression when the VariableDeclaration is executed, not when the variable is created.

The variable's value (Initializer) is assigned to it during the Execution Phase, not the Creation Phase of the Execution Context. Variables declared with the let and const keywords behave identically.

var variable = 42

// Global Execution Context Creation Phase
{
    // Environment Record
    {
        identifier: variable
        value: undefined
    }
    [[OuterEnv]]: null
}

// Global Execution Context Execution Phase
{
    // Environment Record
    {
        identifier: variable
        value: 42
    }
    [[OuterEnv]]: null
}

Diffrences

To sum up the article, I would like to highlight the following differences:

Scope

The first difference between variables created with var, let, and const keywords is how they are scoped. Variables created with let and const are scoped to the LexicalEnvironment, meaning they are available in the Environment Record of a block, function, or the Global Execution Context. In contrast, variables created with var are scoped to the VariableEnvironment, meaning they are only available in the Environment Record of a function or the Global Execution Context.

Creation Phase of the Execution Context

During the Execution Context's Creation Phase, variables created with let and const are uninitialised, whilst var variables are assigned the undefined value. The state of let and const being uninitialised is sometimes referenced as a Temporal Dead Zone or TDZ. Also, the behaviour of var being assigned the undefined value is usually known as “hoisting”.

Default Initializer value

Variables created with let and var keywords are assigned the undefined value if Initializer is not provided. Meanwhile, const variables must always have Initializer.

Variables naming

Variables created with the var keyword can have duplicate names since they all reference the same variable. However, let and const variables can't have duplicate names — doing so results in a Syntax Error.

Variables Initializer reassignment

Variables created with let and var keywords can reassign their initial Initializer (value) to a different one. But, const variables can't have their Initializer reassigned.

版本声明 本文转载于:https://dev.to/rmnkk/the-differences-between-var-let-and-const-through-the-prism-of-the-ecmascript-standard-26dh?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 为什么Microsoft Visual C ++无法正确实现两台模板的实例?
    为什么Microsoft Visual C ++无法正确实现两台模板的实例?
    The Mystery of "Broken" Two-Phase Template Instantiation in Microsoft Visual C Problem Statement:Users commonly express concerns that Micro...
    编程 发布于2025-03-12
  • UTF-8 vs. Latin-1:字符编码大揭秘!
    UTF-8 vs. Latin-1:字符编码大揭秘!
    [utf-8和latin1 在他们的应用中,出现了一个基本问题:什么辨别特征区分了这两个编码?超出其字符表现能力,UTF-8具有额外的几个优势。从历史上看,MySQL对UTF-8的支持仅限于每个字符的三个字节,这阻碍了基本多语言平面(BMP)之外的字符的表示。但是,随着MySQL 5.5的出现,...
    编程 发布于2025-03-12
  • 大批
    大批
    [2 数组是对象,因此它们在JS中也具有方法。 切片(开始):在新数组中提取部分数组,而无需突变原始数组。 令ARR = ['a','b','c','d','e']; // USECASE:提取直到索引作...
    编程 发布于2025-03-12
  • 如何在Java字符串中有效替换多个子字符串?
    如何在Java字符串中有效替换多个子字符串?
    在java 中有效地替换多个substring,需要在需要替换一个字符串中的多个substring的情况下,很容易求助于重复应用字符串的刺激力量。 However, this can be inefficient for large strings or when working with nu...
    编程 发布于2025-03-12
  • Part SQL注入系列:高级SQL注入技巧详解
    Part SQL注入系列:高级SQL注入技巧详解
    [2 Waymap pentesting工具:单击此处 trixsec github:单击此处 trixsec电报:单击此处 高级SQL注入利用 - 第7部分:尖端技术和预防 欢迎参与我们SQL注入系列的第7部分!该分期付款将攻击者采用的高级SQL注入技术 1。高...
    编程 发布于2025-03-12
  • 为什么PYTZ最初显示出意外的时区偏移?
    为什么PYTZ最初显示出意外的时区偏移?
    与pytz 最初从pytz获得特定的偏移。例如,亚洲/hong_kong最初显示一个七个小时37分钟的偏移: 差异源利用本地化将时区分配给日期,使用了适当的时区名称和偏移量。但是,直接使用DateTime构造器分配时区不允许进行正确的调整。 example pytz.timezone(...
    编程 发布于2025-03-12
  • 如何修复\“常规错误:2006 MySQL Server在插入数据时已经消失\”?
    如何修复\“常规错误:2006 MySQL Server在插入数据时已经消失\”?
    How to Resolve "General error: 2006 MySQL server has gone away" While Inserting RecordsIntroduction:Inserting data into a MySQL database can...
    编程 发布于2025-03-12
  • 我们如何保护有关恶意内容的文件上传?
    我们如何保护有关恶意内容的文件上传?
    对文件上载上传到服务器的安全性问题可以引入重大的安全风险,因为用户可能会提供潜在的恶意内容。了解这些威胁并实施有效的缓解策略对于维持应用程序的安全性至关重要。用户可以将文件名操作以绕过安全措施。避免将其用于关键目的或使用其原始名称保存文件。用户提供的MIME类型可能不可靠。使用服务器端检查确定实际...
    编程 发布于2025-03-12
  • 如何使用JavaScript中的正则表达式从字符串中删除线路断裂?
    如何使用JavaScript中的正则表达式从字符串中删除线路断裂?
    在此代码方案中删除从字符串在JavaScript中解决此问题,根据操作系统的编码,对线断裂的识别不同。 Windows使用“ \ r \ n”序列,Linux采用“ \ n”,Apple系统使用“ \ r。” 来满足各种线路断裂的变化,可以使用以下正则表达式: [&& && &&&&&&&&&&&...
    编程 发布于2025-03-12
  • 为什么使用Firefox后退按钮时JavaScript执行停止?
    为什么使用Firefox后退按钮时JavaScript执行停止?
    导航历史记录问题:JavaScript使用Firefox Back Back 此行为是由浏览器缓存JavaScript资源引起的。要解决此问题并确保在后续页面访问中执行脚本,Firefox用户应设置一个空功能。 警报'); }; alert('inline Alert')...
    编程 发布于2025-03-12
  • 如何使用PHP将斑点(图像)正确插入MySQL?
    如何使用PHP将斑点(图像)正确插入MySQL?
    essue VALUES('$this->image_id','file_get_contents($tmp_image)')";This code builds a string in PHP, but the function call ...
    编程 发布于2025-03-12
  • 我可以将加密从McRypt迁移到OpenSSL,并使用OpenSSL迁移MCRYPT加密数据?
    我可以将加密从McRypt迁移到OpenSSL,并使用OpenSSL迁移MCRYPT加密数据?
    将我的加密库从mcrypt升级到openssl 问题:是否可以将我的加密库从McRypt升级到OpenSSL?如果是这样,如何?答案:是的,可以将您的Encryption库从McRypt升级到OpenSSL。可以使用openssl。附加说明: [openssl_decrypt()函数要求iv参...
    编程 发布于2025-03-12
  • 在Java中使用for-to-loop和迭代器进行收集遍历之间是否存在性能差异?
    在Java中使用for-to-loop和迭代器进行收集遍历之间是否存在性能差异?
    For Each Loop vs. Iterator: Efficiency in Collection TraversalIntroductionWhen traversing a collection in Java, the choice arises between using a for-...
    编程 发布于2025-03-12
  • 如何检查对象是否具有Python中的特定属性?
    如何检查对象是否具有Python中的特定属性?
    方法来确定对象属性存在寻求一种方法来验证对象中特定属性的存在。考虑以下示例,其中尝试访问不确定属性会引起错误: >>> a = someClass() >>> A.property Trackback(最近的最新电话): 文件“ ”,第1行, AttributeError: SomeClass...
    编程 发布于2025-03-12
  • Java HashSet/LinkedHashSet随机元素获取方法详解
    Java HashSet/LinkedHashSet随机元素获取方法详解
    在编程中找到一个随机元素,在编程中找到一个随机元素,从集合(例如集合)中选择一个随机元素很有用。 Java提供了多种类型的集合,包括障碍物和链接HASHSET。本文将探讨如何从这些特定集合实现的过程中选择一个随机元素。的java的hashset和linkedhashset a HashSet代表...
    编程 发布于2025-03-12

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3