Home > Article > Web Front-end > What are the differences between let and const in es6
Difference: 1. Let declares variables, whose values and types can be changed, while const declares constants, which cannot be changed or reassigned; 2. let variables do not need to be initialized after declaration. As for const constants, once declared, they must be initialized immediately; 3. const always points to a fixed address, while let is not fixed.
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
let and const are two new keywords introduced in es6 to declare variables. Although we can still use the widely known var variable, now we have two more powerful tools. Use: let and const.
The difference between let and const in es6
① Let declares a variable, and its value and type can be changed; const declares A constant whose value and type cannot be changed.
② Let variables do not need to be initialized after being declared, but const constants, once declared, must be initialized immediately and cannot be assigned a value later.
const i ; // 报错,一旦声明,就必须立即初始化 const j = 5; j = 10; // 报错,常量不可以改变
③ const always points to a fixed address, while let is not fixed
const foo = {}; // 为 foo 添加一个属性,可以成功 foo.prop = 123; foo.prop // 123 // 将 foo 指向另一个对象,就会报错 foo = {}; // TypeError: "foo" is read-only
In the above code, the constant foo stores an address, and this address points to an object. What is immutable is only this address, that is, foo cannot be pointed to another address, but the object itself is mutable, so new properties can still be added to it.
Note:
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
The similarities between let and const in es6:
① Only valid within the block-level scope where the declaration is located.
② There is no declaration promotion, and there is a temporary dead zone, which can only be used after the declared position.
<script type="text/javascript"> console.log(dadi); let dadi = 569; </script>
Result: An error will be reported
③ Repeatable declaration is not allowed.
【Related recommendations: javascript video tutorial, web front-end】
The above is the detailed content of What are the differences between let and const in es6. For more information, please follow other related articles on the PHP Chinese website!