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对象 ,这意味着浏览器中的window
。 let
不能以这种方式工作; 该变量可用,但未附加到全局对象,因此无法从文件外部访问。