In JavaScript, let
, const
and var
are keywords used to declare variables. They have different characteristics in terms of scope, variable hoisting, mutability, and repeated declarations.
the difference:
- Scope:
let
andconst
both are block-level scoped variables,var
but function-scoped variables. Block-level scope means thatlet
the and are valid withinconst
the block (curly braces) in which they are declared , and are invalid beyond that block.{}
The function scope means thatvar
it is valid in the whole function body. - Variable Hoisting:
var
There is variable hoisting, i.e. variables can be used before they are declared. Andlet
withoutconst
variable hoisting, using a variable before it is declared causes an error to be thrown. - Mutability:
let
andvar
declared variables can be reassigned, whileconst
declared variables are constants and cannot be reassigned. Note thatconst
a declared object or array can still have its properties or elements modified, but it cannot be reassigned as a new object or array. - Repeated declaration: In the same scope,
var
the same variable name can be declared multiple times, andlet
theconst
same variable name is not allowed to be declared repeatedly in the same scope.
connect:
- Declaration method: They are both used to declare variables, but the syntax used is slightly different.
let
: Used to declare modifiable variables with block-level scope.const
: Used to declare constants, which cannot be reassigned after declaration, and also have block-level scope.var
: Used to declare variables with function scope.
- Variable redefinition: Variables used
let
andconst
declared cannot be defined repeatedly, which will lead to errors. However,var
multiple definitions of the same variable are allowed, and subsequent definitions will override previous definitions.
General recommendation:
- Use
let
andconst
replace whenever possiblevar
, as they are safer and more flexible. - Use to
let
declare variables that need to be modified. - Use
const
declared constants that will not be reassigned. - Only use when you really need function scope
var
.
When declaring variables, you can choose to use let
, const
or , depending on the situation var
. Here are some usage examples:
1. Use let:
let age = 25;
age = 26; // 可以重新赋值
console.log(age); // 输出 26
function updateName() {
let name = "John";
console.log(name);
}
updateName(); // 输出 "John"
console.log(name); // 报错,name 不在作用域内
2. Use const:
const PI = 3.14;
console.log(PI); // 输出 3.14
// 声明常量后不能再次赋值
PI = 3.14159; // 报错,不允许改变值
const person = {
name: "Alice",
age: 30
};
person.age = 31; // 对象的属性可以修改
person.city = "New York"; // 可以添加新的属性
console.log(person); // 输出 { name: "Alice", age: 31, city: "New York" }
3. Use var:
var count = 10;
count = 11; // 可以重新赋值
console.log(count); // 输出 11
function sayHello() {
var message = "Hello!";
console.log(message);
}
sayHello(); // 输出 "Hello!"
console.log(message); // 报错,message 不在作用域内