JavaScript 变量
如何 declare 变量使用 let, const, and var, and 规则那个 govern 它们.
你将学到
- difference 之间 var, let, and const
- 变量 naming 规则 and 约定
- 块作用域对比函数作用域
- Hoisting and temporal dead 区域
- 当到 reassign and 当到 keep 变量常量
概念讲解
Three Ways to Declare Variables
Modern JavaScript provides three keywords for declaring variables:
let— a variable that can be reassigned. Scoped to the block ({ ... }) where it is declared.const— a variable that cannot be reassigned. Also block-scoped. Use this by default.var— the old way (pre-ES6). Function-scoped, hoisted, and can cause subtle bugs. Avoid in modern code.
let score = 10;
score = 20; // OK — let allows reassignment
const PI = 3.14159;
// PI = 3; // TypeError — const cannot be reassigned
var legacy = "avoid me";
Naming Rules
Variable names (identifiers) must:
- Start with a letter,
$, or_(not a digit) - Contain only letters, digits,
$, and_ - Not be a reserved word (
类,返回,如果, etc.) - Be case-sensitive (
ageandAgeare different variables)
Conventions: use camelCase for variables and UPPER_SNAKE_CASE for constants that are truly constant (like MAX_RETRY_COUNT).
Scope
let and const are block-scoped — they only exist inside the { } block where they are declared. var is function-scoped, which means it leaks out of blocks:
if (true) {
let blockScoped = "仅这里";
var functionScoped = "leaks out";
}
console.log(functionScoped); // "leaks out"
// console.log(blockScoped); // ReferenceError
Hoisting and the Temporal Dead Zone
var declarations are hoisted to the top of their scope and initialized as undefined. let and const are also hoisted but live in the temporal dead zone until their declaration is reached — accessing them early throws a ReferenceError. This is a feature: it prevents you from using a variable before it is defined.
Default to const
A good rule of thumb: use const by default, and switch to let only when you need to reassign. This makes your intent clear and helps prevent accidental mutations. Never use var in new code.
示例代码
// Good: const by default
const playerName = "Ada";
const maxHealth = 100;
// Use let when you need to reassign
let currentHealth = 100;
currentHealth = currentHealth - 25; // took damage
console.log(`${playerName} has ${currentHealth}/${maxHealth} HP`);
// const objects can still have their properties mutated
const player = { name: "Ada", level: 1 };
player.level = 2; // OK — we are mutating a property, not reassigning
console.log(player);
// Block scope in action
let message = "outside";
if (true) {
let message = "inside";
console.log(message); // "inside"
}
console.log(message); // "outside"
const prevents reassignment 的 binding, 但 for 对象 and 数组内容能 still 更改. 块作用域平均值 let 内部如果-块是 不同变量从 one 使用相同 name 之外.
动手试一试
- 情况 Converter
变量 naming 约定 (camelCase, snake_case) — convert 文本 live.
- Slugify
Turning 变量-如字符串到 URL-safe slugs.
常见错误
错误写法
Using var 相反的 let or const
正确做法
var 是函数-scoped and hoisted, 哪个 causes subtle bugs. Use const 通过默认 and let 当你 需要到 reassign. 从不 use var in modern code.
错误写法
Thinking const 制作对象不可变
正确做法
const 仅 prevents reassigning 变量它自己. 你能 still mutate 对象属性 and 数组元素. Use 对象.freeze() for 真 immutability.
相关资源
相关速查表
- JavaScript Cheatsheet
变量 declaration 引用 and 作用域规则.
练习 JavaScript 变量
12 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。