Compare the differences between var, let, and const.
ECMAScript 6 introduced the let
and const
keywords, fundamentally changing how variables are declared in JavaScript. Compared to the traditional var
, they exhibit significant differences in scope, hoisting behavior, and redeclaration, making code more predictable and easier to maintain.
Scope Differences
Variables declared with var
have function scope or global scope, while let
and const
have block scope (delimited by {}
).
// Function scope with var
function varExample() {
if (true) {
var x = 10;
}
console.log(x); // Outputs 10 (variable leaks into function scope)
}
// Block scope with let/const
function letExample() {
if (true) {
let y = 20;
const z = 30;
}
console.log(y); // ReferenceError: y is not defined
console.log(z); // ReferenceError: z is not defined
}
Hoisting and Temporal Dead Zone (TDZ)
var
exhibits hoisting, where accessing the variable before declaration yields undefined
. let
and const
are also hoisted but enter a Temporal Dead Zone (TDZ), causing an error if accessed.
console.log(a); // undefined (hoisting)
var a = 1;
console.log(b); // ReferenceError: Cannot access 'b' before initialization
let b = 2;
Redeclaration
var
allows redeclaring the same variable (the latter overwrites the former), while let
and const
prohibit redeclaration within the same scope.
var c = 1;
var c = 2; // Valid
let d = 3;
let d = 4; // SyntaxError: Identifier 'd' has already been declared
Global Object Properties
In the global scope, variables declared with var
become properties of the window
object, whereas let
and const
do not.
var globalVar = 'foo';
let globalLet = 'bar';
console.log(window.globalVar); // 'foo'
console.log(window.globalLet); // undefined
Special Behavior of const
const
declares constants that must be initialized and cannot be reassigned (though properties of objects/arrays can be modified).
const PI = 3.14;
PI = 3.1415; // TypeError: Assignment to constant variable
const obj = { name: 'Alice' };
obj.name = 'Bob'; // Valid (property modification)
obj = {}; // TypeError (reassignment)
Behavior in Loops
In for
loops, var
causes variable sharing, while let
creates a separate binding for each iteration.
// Issue with var
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100); // Outputs 3, 3, 3
}
// Solution with let
for (let j = 0; j < 3; j++) {
setTimeout(() => console.log(j), 100); // Outputs 0, 1, 2
}
Practical Recommendations
- Default to
const
unless reassignment is needed. - Use
let
when reassignment is required. - Avoid
var
(unless legacy compatibility is necessary). - Use
const
for object/array constants.
// Recommended approach
const API_URL = 'https://api.example.com';
let requestCount = 0;
function fetchData() {
requestCount++;
// ...
}
Performance Considerations
Modern JavaScript engines optimize block-scoped variables better. let
and const
run faster in strict mode because their scope is more explicit, making it easier for engines to perform static analysis.
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:变量解构赋值的配合使用
下一篇:箭头函数的基本语法