Skip to content

变量

学习什么变量是, 如何 创建它们, and 如何它们存储数据你的 program 能 reuse.

你将学到

  • 什么变量是 and 为什么我们 use 它们
  • 如何 declare and assign 变量
  • difference 之间 let, const, and var
  • 规则 and 约定 for naming 变量

概念讲解

Variables

variable 是一种 named container for a piece of data. Think of it as a labeled box: you put a value inside, write a name on the box, and later you can look inside by using the name. Without variables, you would have to repeat the same value everywhere — and if it changed, you'd have to find and update every copy.

Declaring and Assigning

In JavaScript you create a variable in two steps (often combined):

let score;          // declare: create the box
score = 0;          // assign: put a value inside
let lives = 3;      // declare + assign in one line

let, const, and var

  • const — the value cannot be reassigned. Use this by default; it prevents accidental changes.
  • let — the value can be reassigned. Use it when the value must change (a counter, a score).
  • var — an older keyword with confusing scoping rules. Avoid it in modern code.

Naming Rules and Conventions

Names must start with a letter, $, or _ — not a number. They cannot contain spaces. By convention, JavaScript uses camelCase: firstName, totalPrice. Choose names that describe the meaning, not the type: userAge is clear; x is not.

Good names make code self-documenting. When you read const maxRetries = 3, you understand the intent without a comment.

示例代码

              const productName = "Notebook";   // const: won't change
let quantity = 2;               // let: will change
const price = 4.99;

let total = quantity * price;   // 9.98
console.log(productName, "x", quantity, "=", total);

quantity = 5;                   // reassign let
total = quantity * price;       // 24.95
console.log(productName, "x", quantity, "=", total);

// productName = "Pen";  // ❌ Error: const cannot be reassigned
            

const 创建 fixed binding; let 创建 changeable one. Notice 我们 recompute 总计之后更改数量 — 变量做 不更新 automatically.

动手试一试

  • 情况 Converter

    变量持有输入文本 and converted result. Try naming 你的 own 测试字符串.

常见错误

错误写法

Using let for 一切, 偶数值 那个从不更改.

正确做法

默认到 const. 切换到 let 仅当 你 actually 需要到 reassign. 这个 catches accidental mutations at 构建时间.

错误写法

Using vague names 如 x, 数据, or temp.

正确做法

Name 变量通过它们的 meaning: invoiceTotal, currentUser, retryCount. Future 你将 thank present 你.

相关速查表

练习 变量

10 个练习

练习 变量

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误