iT邦幫忙

2025 iThome 鐵人賽

DAY 9
0

在 JavaScript 裡,let 是用來 宣告區塊作用域變數 (block scope variable) 的關鍵字。

基本語法

let 變數名稱 = 值;

特點

  1. 區塊作用域
  • let 宣告的變數只在它所在的 程式區塊 {} 中有效。
{
  let x = 10;
  console.log(x); // 10
}
console.log(x); // ❌ ReferenceError: x is not defined
  1. 不可重複宣告
  • 同一作用域內不能用 let 重複宣告同名變數。
let a = 5;
let a = 10; // ❌ SyntaxError: Identifier 'a' has already been declared
  1. 可重新賦值
  • let 宣告的變數可以被重新賦值。
let count = 1;
count = 2; 
console.log(count); // 2
  1. 不會提升 (Hoisting) 到可用狀態
  • let 宣告的變數會被「提升」(hoisted),但在宣告之前使用會報錯(稱為 暫時性死區 TDZ)。
console.log(num); // ❌ ReferenceError
let num = 3;
  1. 適用於迴圈
  • 常見於 for 迴圈中,因為 let 每次迭代都會建立新的作用域。
for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 1000);
}
// 輸出:0, 1, 2

簡單來說:

  • var:函式作用域,允許重複宣告,有提升問題。
  • let:區塊作用域,不能重複宣告,有暫時性死區。
  • const:區塊作用域,不能重複宣告,不能重新賦值。

上一篇
JavaScript 8 種資料類型
系列文
30天絕望倒數JavaScript9
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言