官术网_书友最值得收藏!

Let and const

In ES5 JavaScript, we use the var keyword to define variables. In most cases, var can simply be replaced with let, with the major difference between the two constructs being the scoping of the variable with respect to blocks. The following example from MDN web docs, or previously Mozilla Developer Network (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let), demonstrates the subtle difference between the two:

function varTest() {
var x = 1;
if (true) {
var x = 2; // same variable!
console.log(x); // 2
}
console.log(x); // 2
}

function letTest() {
let x = 1;
if (true) {
let x = 2; // different variable
console.log(x); // 2
}
console.log(x); // 1
}

So, while you must use additional caution in cases like the preceding one, in most cases you can simply replace var with let.

The const keyword, unlike let, defines a variable as a constant; that is, you cannot reassign a variable initialized with const at a later date. For example, the following code causes an error with a message similar to invalid assignment to const a:

const a = 1;
a = 2;

On the other hand the same code, using var or let to define a, would run successfully.

Note that if a is an object, you are allowed to modify object properties of a.

The following code will run successfully:

const obj = {};
obj.name = ‘My Object’;

However, attempting to redefine objects such as in obj = {name: “other object”} would cause an error.

I find that in most programming contexts, const is typically more appropriate than let, as most variables you use never need to be redefined. My recommendation is to use const as much as you can, and use let only when you have a reason to redefine the variable later.

主站蜘蛛池模板: 启东市| 垫江县| 吉安市| 麟游县| 岑巩县| 阿克陶县| 岚皋县| 遵义县| 湘乡市| 莆田市| 营口市| 伊吾县| 耒阳市| 武宁县| 乌恰县| 呼和浩特市| 鲜城| 社旗县| 惠州市| 舒城县| 惠州市| 阳江市| 开阳县| 肃南| 墨竹工卡县| 积石山| 中超| 克什克腾旗| 曲沃县| 宜春市| 霍山县| 安泽县| 鹤庆县| 横山县| 曲周县| 台湾省| 四川省| 五华县| 浙江省| 巴林左旗| 杭锦后旗|