Table of Contents
let
Basic usage
ES6 adds the let command to declare variables. Its usage is similar to var, but the declared variable is only valid within the code block where the let command is located.
Duplicate declarations are not allowed
const
Home Web Front-end JS Tutorial Comparison between let and const in JavaScript ES6

Comparison between let and const in JavaScript ES6

Jul 22, 2017 pm 04:54 PM
const

let

Basic usage

ES6 adds the let command to declare variables. Its usage is similar to var, but the declared variable is only valid within the code block where the let command is located.
{
  let a = 10;
  var b = 1;
}

a // ReferenceError: a is not defined.
b // 1

上面代码在代码块之中,分别用let和var声明了两个变量。然后在代码块之外调用这两个变量,结果let声明的变量报错,var声明的变量返回了正确的值。这表明,let声明的变量只在它所在的代码块有效。

for循环的计数器,就很合适使用let命令。

for (let i = 0; i < 10; i++) {
  // ...
}

console.log(i);
// ReferenceError: i is not defined
上面代码中,计数器i只在for循环体内有效,在循环体外引用就会报错。

下面的代码如果使用var,最后输出的是10。

var a = [];
for (var i = 0; i < 10; i++) {
  a[i] = function () {
    console.log(i);
  };
}
a[6](); // 10
上面代码中,变量i是var命令声明的,在全局范围内都有效,所以全局只有一个变量i。每一次循环,变量i的值都会发生改变,而循环内被赋给数组a的函数内部的console.log(i),里面的i指向的就是全局的i。也就是说,所有数组a的成员里面的i,指向的都是同一个i,导致运行时输出的是最后一轮的i的值,也就是10。

如果使用let,声明的变量仅在块级作用域内有效,最后输出的是6。

var a = [];
for (let i = 0; i < 10; i++) {
  a[i] = function () {
    console.log(i);
  };
}
a[6](); // 6
上面代码中,变量i是let声明的,当前的i只在本轮循环有效,所以每一次循环的i其实都是一个新的变量,所以最后输出的是6。你可能会问,如果每一轮循环的变量i都是重新声明的,那它怎么知道上一轮循环的值,从而计算出本轮循环的值?这是因为 JavaScript 引擎内部会记住上一轮循环的值,初始化本轮的变量i时,就在上一轮循环的基础上进行计算。

另外,for循环还有一个特别之处,就是设置循环变量的那部分是一个父作用域,而循环体内部是一个单独的子作用域。

for (let i = 0; i < 3; i++) {
  let i = 'abc';
  console.log(i);
}
// abc
// abc
// abc
上面代码正确运行,输出了3次abc。这表明函数内部的变量i与循环变量i不在同一个作用域,有各自单独的作用域。
Copy after login

Duplicate declarations are not allowed

let不允许在相同作用域内,重复声明同一个变量。

// 报错
function () {
  let a = 10;
  var a = 1;
}

// 报错
function () {
  let a = 10;
  let a = 1;
}
因此,不能在函数内部重新声明参数。

function func(arg) {
  let arg; // 报错
}

function func(arg) {
  {
    let arg; // 不报错
  }
}
Copy after login

const

Basic usage

const声明一个只读的常量。一旦声明,常量的值就不能改变。

const PI = 3.1415;
PI // 3.1415

PI = 3;
// TypeError: Assignment to constant variable.
上面代码表明改变常量的值会报错。

const声明的变量不得改变值,这意味着,const一旦声明变量,就必须立即初始化,不能留到以后赋值。

const foo;
// SyntaxError: Missing initializer in const declaration
上面代码表示,对于const来说,只声明不赋值,就会报错。

const的作用域与let命令相同:只在声明所在的块级作用域内有效。

if (true) {
  const MAX = 5;
}

MAX // Uncaught ReferenceError: MAX is not defined
const命令声明的常量也是不提升,同样存在暂时性死区,只能在声明的位置后面使用。

if (true) {
  console.log(MAX); // ReferenceError
  const MAX = 5;
}
上面代码在常量MAX声明之前就调用,结果报错。

const声明的常量,也与let一样不可重复声明。

var message = "Hello!";
let age = 25;

// 以下两行都会报错
const message = "Goodbye!";
const age = 30;
Copy after login

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

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Deep understanding of const in C language Deep understanding of const in C language Feb 18, 2024 pm 12:56 PM

Detailed explanation and code examples of const in C In C language, the const keyword is used to define constants, which means that the value of the variable cannot be modified during program execution. The const keyword can be used to modify variables, function parameters, and function return values. This article will provide a detailed analysis of the use of the const keyword in C language and provide specific code examples. const modified variable When const is used to modify a variable, it means that the variable is a read-only variable and cannot be modified once it is assigned a value. For example: constint

Let's talk about the differences between var, let and const (code example) Let's talk about the differences between var, let and const (code example) Jan 06, 2023 pm 04:25 PM

This article brings you relevant knowledge about JavaScript. It mainly introduces the differences between var, let and const, as well as the relationship between ECMAScript and JavaScript. Interested friends can take a look at it. I hope Helpful to everyone.

How to use const in c language How to use const in c language Sep 20, 2023 pm 01:34 PM

const is a keyword that can be used to declare constants, const modifiers in function parameters, const modified function return values, and const modified pointers. Detailed introduction: 1. Declare constants. The const keyword can be used to declare constants. The value of the constant cannot be modified during the running of the program. The constant can be a basic data type, such as integer, floating point number, character, etc., or a custom data type; 2. The const modifier in the function parameters. The const keyword can be used in the parameters of the function, indicating that the parameter cannot be modified inside the function, etc.

18 Ways to Fix Audio Service Not Responding Issue on Windows 11 18 Ways to Fix Audio Service Not Responding Issue on Windows 11 Jun 05, 2023 pm 10:23 PM

Audio output and input require specific drivers and services to work as expected on Windows 11. These sometimes end up running into errors in the background, causing audio issues like no audio output, missing audio devices, distorted audio, etc. How to Fix Audio Service Not Responding on Windows 11 We recommend you to start with the fixes mentioned below and work your way through the list until you manage to resolve your issue. The audio service may become unresponsive for a number of reasons on Windows 11. This list will help you verify and fix most issues that prevent audio services from responding on Windows 11. Please follow the relevant sections below to help you through the process. Method 1: Restart the audio service. You may encounter

C++ syntax error: const objects must be initialized when defined, how to deal with it? C++ syntax error: const objects must be initialized when defined, how to deal with it? Aug 22, 2023 am 09:13 AM

For C++ programmers, syntax errors are one of the most common problems. One of the common mistakes is that const objects must be initialized at definition time. If you encounter this situation, how should you deal with it? First, we need to understand what a const object is. The const keyword is a special type qualifier in C++ that specifies that the value of a variable cannot be changed during the execution of the program. Such variables are called "constants". If you define a const object without initializing it, you will encounter the above error. This is

What are the correct uses of the const keyword in C++ functions? What are the correct uses of the const keyword in C++ functions? Apr 11, 2024 pm 02:36 PM

Correct usage of the const keyword in C++: Using const to modify a function means that the function will not modify the parameters or class members passed in. Using const to declare a function pointer means that the pointer points to a constant function.

C++ error: Cannot convert const object to non-const object, how to solve it? C++ error: Cannot convert const object to non-const object, how to solve it? Aug 22, 2023 am 08:33 AM

As a strongly typed language, C++ needs to consider many details when performing type conversion. A common problem is that const objects cannot be converted into non-const objects. This problem is more common when pointers and references are involved. Next, we will detail the causes and solutions to this problem. The cause of the problem is that the const keyword in C++ is used to define constants. Once a constant is defined, it cannot be modified. When we convert a const object to a non-const object, we are actually trying to modify a

Usage of const pointers and immutable objects in C++ Usage of const pointers and immutable objects in C++ Jun 06, 2024 am 10:30 AM

In C++, const pointers point to unmodifiable data, while immutable objects have the characteristics that they cannot be modified. The main advantages are: const pointers: prevent the data pointed to from being accidentally written and ensure data integrity. Immutable objects: By making class member variables const, objects that cannot be modified are created to ensure data security.

See all articles