Home >Web Front-end >JS Tutorial >ES6 in Action: let and const

ES6 in Action: let and const

Lisa Kudrow
Lisa KudrowOriginal
2025-02-15 10:12:11898browse

ES6 in Action: let and const

Key Points of let and const in

in ES6

let constES6 introduces two new keywords

and

, which provide a way to define block-scoped variables and constants, enhances JavaScript's capabilities and reduces potential errors. let let

keywords allow variables to be declared within a specific block scope, which is a significant change from JavaScript's previous limitations that are limited to functions and global scopes. Variables declared with

are not hoisted, meaning they cannot be referenced before being declared within a block. const constObject.freeze() Keywords are used to define constants that cannot be redeclared. Although let creates an immutable binding, it does not make the value itself immutable. To achieve value immutability, const should be used.

and

are supported in Node and in all modern browsers. let constThis tutorial will introduce

and

, two keywords that are new keywords added to JavaScript in ES6. They enhance JavaScript by providing a way to define block-scoped variables and constants. Map WeakMapThis article is one of many articles about the new JavaScript introduced in ES6, including Set and WeakSet, String and Number, available for Array,

and

new methods and new syntax that can be used for functions. let

<code class="language-javascript">function foo() {
  var par = 1;
  if (par >= 0) {
    var bar = 2;
    console.log(par); // 输出 1
    console.log(bar); // 输出 2
  }
  console.log(par); // 输出 1
  console.log(bar); // 输出 2
}
foo();</code>
Before ES5, JavaScript had only two scopes: function scope and global scope. This brings a lot of frustration and unexpected behavior to developers from other languages ​​such as C, C, or Java. JavaScript lacks block scope, which means that variables can only be accessed within the blocks it defines. Blocks are everything in a pair of curly braces. Let's look at the following example:

<code>1
2
1
2</code>
After running this code, you will see the following output in the console:

if barMost developers from the above languages ​​expect that the bar variables are not accessible outside the if block. For example, running the equivalent code in C results in an error "bar not declared", which refers to using

outside the block.

This situation changes in ES6 with the availability of block scope. ECMA organization members know that they cannot change the behavior of the keyword var because this breaks backward compatibility. So they decided to introduce a new keyword called let. The latter can be used to define variables, limiting their scope to blocks that declare them. Furthermore, unlike var, variables declared using let will not be promoted. If you reference a variable in the block before encountering the let declaration of the variable, it will result in ReferenceError. But what does this mean in practice? Is it only good for newbies? not at all!

To explain why you like let, please consider the following code, excerpted from my article "5 JavaScript Interview Exercises":

<code class="language-javascript">function foo() {
  var par = 1;
  if (par >= 0) {
    var bar = 2;
    console.log(par); // 输出 1
    console.log(bar); // 输出 2
  }
  console.log(par); // 输出 1
  console.log(bar); // 输出 2
}
foo();</code>

Here, you can identify a well-known problem related to variable declarations, scopes, and event handlers. If you don't know what I'm talking about, check out the article I mentioned before coming back.

Thanks to ES6, we can easily solve this problem by using the for declare the let variable in the i loop:

<code>1
2
1
2</code>

let statements are supported in Node and in all modern browsers. However, there are some things to note in Internet Explorer 11 that you can read about in the ES6 compatibility table.

A real-time demonstration of the difference between var and let is shown below, which is also located on JSBin.

const

const Addresses common demands for developers to associate a mnemonic with a given value so that the value cannot be changed (or, more simply, define a constant). For example, if you use mathematical formulas, you might want to create a Math object. In this object, you want to associate the values ​​of π and e with the mnemonic. const Allows you to achieve this goal. Using it, you can create a constant that can be global or a local variable of the function that declares it.

Constants defined with const follow the same scope rules as variables, but they cannot be redeclared. Constants also share a property with variables declared using let, that is, they are block-scoped rather than function-scoped (so they are not promoted). If you try to access the constant before declaring it, you will receive ReferenceError. If you try to assign a different value to a variable declared with const, you will receive TypeError.

However, please note that const has nothing to do with immutability. As Mathias Bynens said in his blog post ES2015 const has nothing to do with immutability, const creates an immutable binding, but this does not mean that the value is immutable, as shown in the following code:

<code class="language-javascript">var nodes = document.getElementsByTagName('button');
for (var i = 0; i < nodes.length; i++) {
  nodes[i].addEventListener('click', function() {
    console.log('您点击了元素 #' + i);
  });
}</code>

If you want to make the object's value truly immutable, use Object.freeze().

const's browser support is as good as let. const statements are supported in Node and in all modern browsers. However, here, Internet Explorer 11 also has some things to note, and you can read the relevant information in the ES6 compatibility table.

A sample usage of const is shown below:

<code class="language-javascript">function foo() {
  var par = 1;
  if (par >= 0) {
    var bar = 2;
    console.log(par); // 输出 1
    console.log(bar); // 输出 2
  }
  console.log(par); // 输出 1
  console.log(bar); // 输出 2
}
foo();</code>

The following shows a live demonstration of the previous code, which is also located on JSBin.

Conclusion

In this tutorial, I introduced you to let and const, two new ways to declare variables introduced in ES6. While var won't disappear anytime soon, I encourage you to use const and let wherever possible to reduce the possibility of code errors. As a further reading, you might also like our quick tip How to declare variables in JavaScript, which explores the mechanisms of variable declarations in more depth.

FAQs (FAQs) about ES6 letconst What is the difference between

,

and var in JavaScript ES6? let constIn JavaScript ES6,

,

, and var are used to declare variables. The main difference between them is their scope and reassignment. let is function-scoped, meaning it is only available within the functions it declares. On the other hand, const and var are block-scoped, meaning they are only available within the blocks they declare. As for reassignment, variables declared with let and const can be reassigned, while variables declared with var cannot. This makes let very suitable for values ​​that should be kept unchanged throughout the program. const constWhen should I use

and

in my code? let const When you need to declare a variable that changes over time, such as a counter in a loop or a value swap in an algorithm, you should use

. When you have a value that is known to not change, such as configuration settings or references to DOM elements, you should use

. Using let can make your code easier to read and understand because it shows other developers that the value should not be changed. const constCan I reassign the

variable in JavaScript ES6?

constNo, you cannot reassign

variables in JavaScript ES6. Once the

variable is assigned, attempting to reassign will result in const. However, if the const variable is an object, you can change the properties of the object, but not the object itself. TypeError constWhat is the scope of the

variable in JavaScript ES6?

letIn JavaScript ES6, the

variable has a block scope. This means it can only be accessed within the code block it defines. If you try to access it outside its block, you will receive

. let

What happens if I declare a variable using let or const without initialization?

If you declare a variable using let or const without initialization, it will be undefined. However, unlike var, you cannot use let or const variables before declaring them. Doing so will result in ReferenceError.

Can I declare variables with the same name using let or const within the same scope?

No, you cannot declare variables with the same name using let or const within the same scope. Doing so will result in SyntaxError. This is called the "Temporal Dead Zone" rule.

In the context of let and const, what is the promotion?

Elevation is a mechanism in JavaScript where variables and function declarations are moved to the top of their included scope during the compilation phase. However, unlike var, the let and const declarations are not initialized. They are promoted, but you cannot access them before the declaration, because they are in a "temporary dead zone" from the beginning of the block until the declaration is processed.

Can I use let and const in all browsers?

let and const are part of the ES6 (ES2015) specification and are supported in all modern browsers. However, for older browsers that do not support ES6, you need to convert ES6 code to ES5 code using a translator such as Babel.

What is the performance impact of using let and const?

The performance impact of using let and const is negligible. The JavaScript engine optimizes for these keywords, so there is no significant performance difference between them and var. The choice between let, const and var should be based on their scope rules and reassignment behavior, not performance.

What are some best practices for using let and const in JavaScript ES6?

Some best practices for using let and const in JavaScript ES6 include using const by default, and only if you know you need to change the amount. This can make your code more predictable and easier to understand. Also, always declare variables at the top of their scope to clarify where they are available. let

The above is the detailed content of ES6 in Action: let and const. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn