There is more than one way to declare a variable in JavaScript, it uses the var, let and const keywords for variable declarations and they all behave differently. I will try to explain them and their different behaviors but before I do that, I would like to explain some concepts that you will come across in trying to understand the various variable declarations, these are Scope and Hoisting.
在JavaScript中声明变量的方法不止一种,它使用var , let和const关键字进行变量声明,并且它们的行为都不同。 我将尝试解释它们及其不同的行为,但在此之前,我想解释一些在理解各种变量声明时会遇到的概念,这些是Scope和Hoisting 。
Scope -The scope of a variable or function is the part of the code where the variable is visible or accessible. So it simply means variable access, that is, what variables do I have access to where the code is running. When a variable is not declared within a function, it is said to have a global scope, is assigned to the global object and can be accessed or referenced from anywhere. A variable declared within a function is said to have a local scope and can only be accessed inside the function.
作用域-变量或函数的作用域是代码可见或可访问的部分。 因此,这仅表示变量访问,也就是说,我可以访问代码运行位置的变量。 如果未在函数中声明变量,则称该变量具有全局作用域,已分配给全局对象,并且可以从任何地方访问或引用。 声明在函数内声明的变量具有局部作用域,并且只能在函数内部访问。
var outside = "globally scoped"; //I am a global variable function someFunction() { var inside = "locally scoped"; //I am a local variable console.log(inside); //This prints "locally scoped" console.log(outside); //This prints "globally scoped" as the variable is a global variable and can be accessed from anywhere } console.log(outside)//Still prints "globally scoped" console.log(inside) //causes an error because the variable is not accessible from outside the someFunction function where it was declaredHoisting -This suggests that before code execution all variable or function declarations are moved to the top of the code. Technically, they are put into memory but stay exactly where you typed them in your code. Hoisting allows you to use functions before you declare them, so you can doing something like this would be valid:
提升-这建议在代码执行之前,将所有变量或函数声明移到代码顶部。 从技术上讲,它们已存储在内存中,但仍保持在您在代码中键入它们的位置。 提升允许您在声明函数之前使用函数,因此可以执行如下操作:
someFunction()function someFunction(){ //do something} name = "Akin"; console.log(name); var name;// Akin gets printed out, so the declaration gets hoistedSo now we can move on to the different methods of declaring variables in JavaScript
因此,现在我们可以继续介绍JavaScript中声明变量的不同方法
Var -var is traditionally function scoped, variable declared with var outside any function has a global scope and is visible everywhere. A variable declared with var inside a function is assigned to that function, it is local and is visible only inside the function just like a function argument or parameter.If a variable is declared in a function with the same name as a global variable, it takes precedence over the global variable, shadowing it. Var is function scoped not block-scoped so if you don’t create a new function, you don’t get a new scope, a block (identified by a pair of curly braces ({})) does not define a new scope, so things like if statements don’t actually create a new scope.In JS all variables defined with the var keyword have an initial value of “undefined”, this is due to hoisting which puts them in the memory with an initial value of undefined.Var is a less than ideal way to create a variable as you can redeclare a variable that has already been created and not get an error.
var- var传统上是函数范围的,用var声明的变量在任何函数之外都具有全局范围,并且在任何地方都可见。 将在函数内部用var声明的变量分配给该函数,该变量是局部变量,仅在函数内部可见,就像函数的参数或参数一样。如果在函数中声明的变量与全局变量同名,则它将优先于全局变量,并对其进行阴影处理。 Var的作用域范围不是块作用域范围,因此,如果您不创建新函数,就不会获得新作用域,块(由一对大括号({})标识)不会定义新作用域,因此,诸如if语句之类的事情实际上并没有创建新的作用域。在JS中,使用var关键字定义的所有变量的初始值均为“ undefined”,这是由于提升将其以undefined的初始值放入内存中。 Var是一种不太理想的创建变量的方法,因为您可以重新声明已经创建的变量并且不会出错。
if(10 === 10){ var name = 'Akin'; } console.log(name);//will be able to access name var setName = function(){ var name = 'Akin'; } setName(); console.log(name); //will return an error, won't be able to access the variable name because var is function scoped var firstName = 'Akin'; var firstName = 'Goody'; //Redeclaring is valid when using var as it doen't return any error and this could cause a lot of problemsLet -This is a new way of declaring variables in JavaScript. It is the block-scoped version of Var. Block means anything surrounded by curly braces {}. So with let, things like if statements and for loops create new scopes. Defining a variable outside a function using let unlike var doesn’t create a global variable. A variable declared using let can be reassigned just like with var but it can’t be redeclared, trying to redeclare a variable created using let will return an error. like var, variables declared using let are also hoisted but uninitialized variables don’t have an initial value of “undefined”. With let, when you reference uninitialized variable, you get a ReferenceError.
Let-这是在JavaScript中声明变量的新方法。 它是Var的块范围版本。 块表示由花括号{}包围的所有内容。 因此,使用let时,诸如if语句和for循环之类的事情会创建新的作用域。 与var不同,使用let定义函数外部的变量不会创建全局变量。 可以像使用var一样重新分配使用let声明的变量,但是无法重新声明,尝试重新声明使用let创建的变量将返回错误。 与var一样,使用let声明的变量也将被挂起,但未初始化的变量的初始值不会为“ undefined”。 使用let时,当您引用未初始化的变量时,将得到ReferenceError。
if(10 === 10){ let name = 'Akin'; } console.log(name);//will not be able to access name as let is block scoped let setName = function(){ let name = 'Akin'; } setName(); console.log(name); //will return an error let firstName = 'Akin'; let firstName = 'Goody'; //Redeclaring will cause an error using letConst -This keyword is used to declare constants i.e. variables that are not going to change. Variables created using const can’t be changed or reassigned to a different value. It doesn’t provide immutability, it just makes sure that the reference can’t be changed; that is to say, that with constant you can change the properties of the constant if it an object, you just can’t reassign the variable. Const is block-scoped like let. If you have anything that isn’t going to change, it should be a constant as it is a lot safer declaring it like that so that nobody assigns something else to the variable name.Const variables are also hoisted but not assigned as with let.
常量-此关键字用于声明常量,即不会更改的变量。 使用const创建的变量不能更改或重新分配为其他值。 它不提供不变性,只是确保引用不能被更改。 也就是说,使用常量可以更改常量的属性(如果它是对象),则无法重新分配变量。 const像let一样是块状的。 如果您有什么需要修改的地方,它应该是一个常量,因为这样更安全地声明它,这样就没有人为变量名分配其他内容。常量变量也被提升但不像let那样分配。
if(10 === 10){ const name = 'Akin'; } console.log(name);//like let, const is also block scoped const setName = function(){ const name = 'Akin'; } setName(); console.log(name); //will return an error as you are trying to access was defined in a different scope const firstName = 'Akin'; const firstName = 'Goody'; //Redeclaring will cause an error using const firstName = "Obi"; //Will return an error as you can't reassign a constant variable const someObject = { name: 'Anton', age: 26 } someObject.age = 28; console.log(someObject.age); //Prints 28, as properties of an object declared with const can still be changed, the variable jsut can't be reassignedSummaryVar is function scoped and an uninitialized var variable is assigned the value of undefined. Let and const were introduced in ES6, they are both block-scoped and can’t be redeclared, trying to access an uninitialized const or let variable will return a ReferenceError. Variables declared with let can be reassigned but with const, they can’t be.
总结Var是函数范围的,未初始化的var变量被赋值为undefined。 在ES6中引入了let和const,它们都是基于块的并且无法重新声明,因此尝试访问未初始化的const或let变量将返回ReferenceError。 可以重新分配用let声明的变量,但不能使用const进行赋值。
翻译自: https://medium.com/@goodnesschrisugari/understanding-var-let-and-const-in-javascript-4a7f030c02ff
相关资源:了解javascript中let和var及const关键字的区别