Home > Web Front-end > JS Tutorial > body text

What is the difference between let and const

青灯夜游
Release: 2023-01-04 09:37:59
Original
18696 people have browsed it

Difference: Variables declared by let can be changed, and both value and type can be changed; while constants declared by const cannot be changed, which means that once const is declared, it must be initialized immediately and cannot be assigned a value later.

What is the difference between let and const

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Related recommendations: "javascript video tutorial"

The difference between let and const:

① The variables declared by let can be changed, and both the value and type can be changed; the constants declared by const cannot be changed, which means that once const is declared, it must be initialized immediately and cannot be assigned a value later.

const i ; // 报错,一旦声明,就必须立即初始化
const j = 5;
j = 10; // 报错,常量不可以改变
Copy after login

②For composite type variables such as arrays and objects, the variable name does not point to the data, but to the address where the data is located. const only guarantees that the address pointed to by the variable name remains unchanged, but does not guarantee that the data at that address remains unchanged, so you must be very careful when declaring a composite type variable as a constant.

const arr = [];
// 报错,[1,2,3]与[]不是同一个地址
arr = [1,2,3];
const arr = [];
// 不报错,变量名arr指向的地址不变,只是数据改变
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
console.log(arr.length); // 输出:3
Copy after login

If you want the data of the defined object or array not to change, you can use object.freeze(arr) to freeze. Freezing means that new attributes cannot be added to this object or array, the values ​​of existing attributes cannot be modified, and existing attributes cannot be deleted.

const arr = [];
Object.freeze(arr);
// 不报错,但数据改变无效
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
console.log(arr.length); // 输出:0
Copy after login

The similarities between let and const:

① It is only valid within the block-level scope where it is declared.

② No promotion, and there is a temporary dead zone, which can only be used after the declared position.

③ Cannot be repeated.

For more programming-related knowledge, please visit: Introduction to Programming! !

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

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template