学习库JavaScriptVariables

Variables

Choose between const and let, understand scope, and give values useful names.

更新于 适用于 ECMAScript 2026

JavaScript variables give names to values. Start with const and reach for let only when the name needs to point somewhere else later.

Prefer const

profile.js
const name = "Mina";
let lessonsRead = 3;

Change with intent

Use let for state that genuinely changes, such as a counter.

counter.js
let count = 0;
count = count + 1;

Block scope

Both const and let belong to the nearest block. A value declared inside an if statement is unavailable outside it.

scope.js
const signedIn = true;

if (signedIn) {
  const message = "Welcome back";
  console.log(message);
}

Use names that describe the value's role: lessonCount is clearer than x. Boolean names often read well as questions such as isReady or hasAccess.

profile.js
const profile = { name: "Mina", lessonsRead: 3 };
const { name, lessonsRead } = profile;

Keep this

  • Default to const.
  • Use let for reassignment.
  • Avoid var in modern code.
  • Keep scope small and names specific.
学习位置已保存在此设备上。