Skip to content

建立 2026-09-12 更新 2026-09-12

變數

變數是給資料取的名字,之後才能拿這個名字來用,不必每次重寫數字或文字。Node.js 請用 letconst;舊的 var 作用範圍較難預期,新程式不要用。

宣告方式

let count = 1;
const name = "Ada";

count = 2;
console.log(count, name);
關鍵字 之後能不能改成別的值 何時用
const 不能再寫 name = ... 預設用這個
let 可以再指定,例如 count = 2 值真的會變時才用

const 不是說裡面的資料不能動。陣列、物件用 const 宣告後,不能換成另一個全新的陣列/物件,但裡面的項目仍可增減或修改:

const list = [1, 2];
list.push(3);      // 可以
// list = [];      // 錯誤

命名規則

  • 可由字母、數字、$_ 組成,不能以數字開頭。
  • 不能使用保留字(例如 letiffunction)。
  • 建議用小駝峰:userNamefileCount
  • 名稱要能看出意思;x1 只適合極短的迴圈計數。
const userName = "Ada";
let fileCount = 0;

範例

const title = "Node.js";
let score = 80;
score = score + 10;
console.log(title, score);

總結

能不變就用 const,會變才用 let。名稱清楚,後面讀程式會輕鬆很多。