March 18, 2025

JS - var let const


[筆記]JS-無宣告/var/let/const

https://dev.to/niharrs/demystifying-var-let-and-const-1olf

先前並沒有把 JS 基礎打好,因此在面試的時候對於作用域的概念有點一知半解,所以還是需要做個筆記稍微歸類一下,如果有錯誤的地方還麻煩指正一下=) 大大感謝。

內容將會隨著實際狀況做變動與更新。


🚩 全域變數(global variables)

但要如何宣告全域變數呢 ?

var x = 100; // 函示外宣告
x = 100; // 無宣告變數
window.x = 100; // 直接產生 window 物件

🚩 無宣告變數

透過 Object.getOwnPropertyDescriptor 或取全域屬性。 無宣告變數 具 ( configurable = true )屬性,代表可以被刪除。

// 無宣告
x = 100;
Object.getOwnPropertyDescriptor(window, "a");
// {value: 6, writable: true, enumerable: true, configurable: true}

已宣告變數 具 (configurable = false) 屬性,代表無法被刪除。

// 已宣告
var x = 999;
Object.getOwnPropertyDescriptor(window, "b");
// {value: 10, writable: true, enumerable: true, configurable: false}

🚫🚫🚫嚴格模式(strict mode 不允許使用未聲明的變量)

✈️ var

特性:⭕️ 可更改內容 ⭕️ 函數變數 ⭕️ 宣告前可使用(不報錯)

console.log(x); // undefined
var x = 999;

var y;
console.log(y); // undefined

**函式(function)「外」**宣告的 var 影響 全域(global scope)

var x = 999;
// --------------------------- ↓ 無 function 屬於 全域(global scope)
if (x) {
  var x = 10;
  console.log(x); // Ans. 10
}
// --------------------------- ↑ 無 function 屬於 全域(global scope)

console.log(x); // Ans. 10

**函式(function)「內」**宣告的 var 影響 函式作用域(function scope)

var x = 999;
// --------------------------- ↓ 有 function 屬於 函式作用域(function scope)
function test() {
  var x = 10;
  console.log(x); // Ans. 10
}
// --------------------------- ↑ 有 function 屬於 函式作用域(function scope)

console.log(x); // Ans. 999

🚕 let _ (ES6)

特性:⭕️ 可更改內容 ⭕️ 區域變數 ⭕️ 需宣告後使用

🚫🚫🚫嚴格模式(strict mode 不允許使用未聲明的變量)

let x;
console.log(x); // undefined

console.log(y); // Uncaught ReferenceError: y is not defined

{ } 內宣告的 let 影響 { } 區域(block scope)。

var x = 999;
// --------------------------- ↓ if 內 {} 區域 可使用 let
if (x) {
  let x = 10;
  console.log(x); // Ans. 10
}
// --------------------------- ↑ if 內 {} 區域 可使用 let

console.log(x); // Ans. 999

無法在同一層區域重複宣告。

let x = 1;
let x = 2;
console.log(x); //  Identifier 'x' has already been declared.

🚌 const _ (ES6)

特性:❌ 不可更改內容 ⭕️ 區域變數 ⭕️ 需宣告後使用

    const x
    // Uncaught SyntaxError: Missing initializer in const declaration

賦值後無法更動(reference 位址 無法更動)。

const x = 100;
x = 999;
// Uncaught TypeError: Assignment to constant variable.

參考資料