var和let和const_如何声明JavaScript变量:看一下let,const和var

var和let和const

by Shirshendu Bhowmick

通过Shirshendu Bhowmick

With the old JavaScript, we had only one way to declare a variable, and that was with var, like var x = 10. It will create a variable called x and assign a value 10 to it. Now with modern ES6 JavaScript, we have 3 different ways to declare a variable: let, const and var. We will talk about let & const later. For now, let's focus on var.

使用旧JavaScript,我们只有一种方法来声明变量,那就是使用var ,例如var x = 10 。 它将创建一个名为x的变量,并为其分配值10。 现在,使用现代ES6 JavaScript,我们有3种不同的方法来声明变量: letconstvar 。 稍后我们将讨论letconst 。 现在,让我们关注var

变种 (var)

We already know how to declare a variable with var. Let us now refer to some code to understand var properly.

我们已经知道如何使用var声明变量。 现在让我们参考一些代码以正确理解var

var x = 20;
function foo() {
    var y = 10;
    console.log(x);
    console.log(y);
}
foo(); // will print 20 and 10
console.log(x); // will print 20
console.log(y); // will throw a reference error

Those who are familiar with C or C++ might understand why the output is like so. This is because x is in global scope and y is in the function foo’s scope. As function foo has access to the global scope, from the inside of the function we can access both x and y. Printing x also goes fine because as x is in global scope, we can access it from everywhere. Things go wrong when we try to access y from the global scope because y is limited to the function scope only.

那些熟悉C或C ++的人可能会理解为什么输出是这样的。 这是因为x在全局范围内,而y在函数foo的范围内。 由于函数foo可以访问全局范围,因此可以从函数内部访问xy 。 打印x也可以,因为x在全局范围内,所以我们可以从任何地方访问它。 当我们尝试从全局范围访问y时,事情会出错,因为y仅限于函数范围。

Similar to C or C++ right? No. Let’s see why not.

类似于C或C ++,对吗? 不,让我们看看为什么不行。

var x = 20;
function foo() {
    var y = 10;
    {
        var z = 30;
    }
    console.log(x);
    console.log(y);
    console.log(z);
}
foo();

What do you think the output of the code will be? If you think that there will be a reference error at the line console.log(z), then you are correct from a C or C++ point of view. But with JavaScript, that’s not the case. The above code will print 20 10 30.

您认为代码的输出是什么? 如果您认为console.log(z)行会出现参考错误,那么从C或C ++的角度来看,您是正确的。 但是,使用JavaScript并非如此。 上面的代码将打印20 10 30。

This is because in JavaScript with var, unlike in C and C++, we don’t have any block level scope. We have only global and function level scope. So z falls under function foo’s scope.

这是因为在具有var JavaScript中,与C和C ++不同,我们没有任何块级范围。 我们只有全局和功能级别范围。 因此z属于函数foo的范围。

Now we have one more example:

现在我们再举一个例子:

var x = 20;
var x = 30;
console.log(x); // this will print 30

In C or C++ if we declare a variable more than once in the same scope we get an error. But that’s not the case with var in JavaScript. In the above example, it just redefines x and assigns a value of 30.

在C或C ++中,如果我们在同一作用域中多次声明一个变量,则会出现错误。 但是JavaScript中的var并非如此。 在上面的示例中,它只是重新定义x并分配值30。

Let’s consider the below code snippets:

让我们考虑以下代码片段:

function foo() {
    x = 20;
    console.log(x);
}
foo();
console.log(x);

The above code will print 20 20. So what happens here? If you declare a variable anywhere without the var keyword it becomes a part of the global scope. It is accessible from both inside and outside of foo.

上面的代码将显示2020。那么这里发生了什么? 如果在没有var关键字的任何地方声明变量,它将成为全局作用域的一部分。 可以从foo内部和外部访问它。

'use strict'
function foo() {
    x = 20;
    console.log(x);
}
foo();
console.log(x);

In the above code, we are using strict mode. In strict mode, an x = 20 kind of declaration is not allowed. It will throw a reference error. You have to declare a variable using var, let or const.

在上面的代码中,我们使用严格模式。 在严格模式下,不允许使用x = 20类型的声明。 它将引发参考错误。 您必须使用varletconst声明变量。

(let)

Now it’s time to have a look at let. let is the new var in ES6 but with some differences.

现在是时候看看letlet是ES6中的新变量,但有所不同。

let x = 20;
function foo() {
    let y = 10;
    {
        let z = 30;
    }
    console.log(x);
    console.log(y);
    console.log(z);
}
foo();

Remember that in JavaScript, var doesn’t have any block-level scope? Now block level scopes are back with let. If you execute the above code you will get a reference error at the line console.log(z). The variable z declared with let is now in a different block-level scope and is not accessible outside of this scope.

还记得在JavaScript中, var没有任何块级范围吗? 现在,使用let返回块级范围。 如果执行上述代码,则在console.log(z)行会出现参考错误。 用let声明的变量z现在处于不同的块级范围内,并且在该范围之外不可访问。

let x = 10;
let x = 20; // will throw an error

Re-declaration of variables with let is not allowed.

不允许使用let重新声明变量。

var x = 10;
let y = 20;
console.log(window.x); // 10
console.log(window.y); // undefined

Global variables declared globally with var are added to the global object, the window in case of browsers. Variables declared globally with let are not added to window (global object). Though they are accessible globally, it's like it’s there but you can’t see it.

使用var全局声明的全局变量将添加到global对象(对于浏览器为window 。 用let全局声明的变量不会添加到window (全局对象)中。 尽管它们可以在全球范围内访问,但就像它在那儿一样,但是您看不到它。

console.log(x); //undefined
console.log(y); //reference error
var x;
let y;

Unlike var, let variables are not initialized with undefined before their definitions are evaluated. If you try to access the variable before that you will encounter a reference error. This is also known as the temporal dead zone. In simple words, hoisting is only available with var, not with let & const.

var不同, let变量在评估其定义之前不会使用undefined进行初始化。 如果在此之前尝试访问变量,将遇到引用错误。 这也称为时间盲区。 简而言之,吊装仅适用于var ,不适用于letconst

const (const)

const stands for constant, it is very similar to let. The only differences are its value cannot be changed and it needs to be initialized where you are declaring it.

const代表常量,它与let非常相似。 唯一的区别是它的值无法更改,需要在声明它的位置进行初始化。

const x = 20;
console.log(x); // will print 20
x = 30 // will throw an error

It’s not that in the case of const objects you can change the property of that object — it’s just that you can’t reassign a const variable.

不是在const对象的情况下您可以更改该对象的属性,而是您不能重新分配const变量。

const obj = {firstName: "James", lastName: "Bond"}
console.log(obj); // will print the obj object
obj.firstName = "Ruskin";
console.log(obj); // will print the obj object, it has new firstName
obj = {firstName: "James", lastName: "Bond"}; // will throw an error

Also as mentioned earlier you have to initialize a const variable, you can’t keep it uninitialized.

同样如前所述,您必须初始化一个const变量,您不能使其保持未初始化状态。

const x; // will throw an error
some other code;

That’s all for this article — see you later!

这就是本文的全部-以后再见!

谢谢您的阅读:) (Thank you for reading :))

翻译自: https://www.freecodecamp.org/news/how-to-declare-javascript-variables-a-look-at-let-const-and-var-5d801c70c377/

var和let和const

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值