在JavaScript中使用let和var有什么区别?

In modern JavaScript we have 3 ways to declare a variable and assign it a value:

在现代JavaScript中,我们有3种方法来声明变量并为其分配值:

  • const

    const

  • let

    let

  • var

    var

When working with variables in JavaScript, I always default to using const. It guarantees the value can’t be reassigned, and so it’s safer to use.

在JavaScript中使用变量时,我始终默认使用const 。 它确保不能重新分配该值,因此使用起来更安全。

But when I do need to redeclare a variable later on, I always use let.

但是,当以后需要重新声明变量时,我总是使用let

I haven’t used var in years, and to me it’s just there for backwards compatibility purposes, and I always raise an eyebrow when I see it used.

我已经好几年没有使用过var了,对我来说,它只是为了向后兼容而已,当我看到它使用时,我总是会大为惊讶。

Why?

为什么?

First, let has sensible scoping.

首先, let进行明智的范围界定

The same scoping that is used in more or less all popular programming languages, block scoping, dictates that variables declared using let are scoped to the nearest block.

或多或少地在所有流行的编程语言中使用相同的作用域,即作用域作用域,指示使用let声明的变量的作用域范围为最近的作用域。

var instead is a bit more weird, as it has function scoping, which means that variables declared using var are scoped to the nearest function.

var有点奇怪,因为它具有函数作用域,这意味着使用var声明的变量的作用域是最接近的函数。

This has practical implications. For example, a variable is declared inside an if or used as the for loop iterator. Using let makes it local to those 2 blocks. Using var, however, allows the variable to be available outside of that block, which might lead to bugs.

这具有实际意义。 例如,变量在if内声明或用作for循环迭代器。 使用let可使它局部于那两个块。 但是,使用var允许该变量在该块之外可用,这可能会导致错误。

Always use the tool that gives you the least amount of power, to make sure you have maximum control over it. With great power comes great responsibility.

始终使用功率最小的工具,以确保对其具有最大的控制权。 权力越大,责任就越大

Another reason to prefer let is hoisting. Like const, let variables are not hoisted, but they are initialized when evaluated.

喜欢let另一个原因是吊装 。 像const一样, let变量不会被悬挂,但是在求值时会被初始化。

var variables instead are hoisted to the top of the function, and as such they are available even in the lines before their declaration. Weird, right?

而是将var变量提升到函数的顶部,因此即使在声明的行中也可以使用它们。 奇怪吧?

Third reason: when you declare a let variable with the same name as one that already exists, you get an error (in Strict Mode).

第三个原因:当声明一个与已经存在的名称同名的let变量时,会出现错误(在严格模式下 )。

Finally, another big difference: if you declare a var variable outside of any function, it’s assigned to the global object, which means window inside the browser. let does not work in this way; the variable is available, but not attached to the global object, and so it’s not reachable from outside of your file.

最后,还有一个很大的不同:如果您在任何函数外部声明一个var变量,它将被分配给global对象 ,这意味着浏览器中的windowlet不能以这种方式工作; 该变量可用,但未附加到全局对象,因此无法从文件外部访问。

翻译自: https://flaviocopes.com/javascript-difference-let-var/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值