Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Undefined trong JavaScript

Thuộc tính undefined

undefined là một **giá trị nguyên thủy (primitive)** đại diện cho "chưa được gán giá trị". Một biến được khai báo nhưng chưa gán giá trị sẽ có giá trị undefined.

Các trường hợp gặp undefined

  • Biến khai báo không gán giá trị: let x;
  • Tham số hàm không truyền: function f(a) { console.log(a); } f();
  • Truy cập property không tồn tại: obj.missingProp
  • Hàm không return (hoặc return không giá trị): function f() {} f()
  • Giá trị của void expression: void 0

Ví dụ minh họa

<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Undefined</title>
    <style>
        body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
        .sample { font-size: 18px; font-weight: 500; color: red; font-family: monospace; }
        button { padding: 8px 16px; cursor: pointer; }
    </style>
</head>
<body>
    <h1>JavaScript undefined</h1>
    <div class="sample"></div>
    <button class="btn-demo">KIỂM TRA BIẾN AGE</button>
    <h3>Nhấn nút để kiểm tra biến age đã được định nghĩa chưa</h3>

    <script>
        const sampleEle = document.querySelector(".sample");
        const btn = document.querySelector(".btn-demo");

        let age; // Khai báo không gán giá trị -> undefined

        btn.addEventListener("click", () => {
            if (age === undefined) {
                sampleEle.textContent = "Biến age chưa được định nghĩa hoặc chưa gán giá trị";
            } else {
                sampleEle.textContent = "Biến age đã định nghĩa, giá trị = " + age;
            }
        });
    </script>
</body>
</html>

undefined vs null

Đặc điểm undefined null
Ý nghĩaChưa gán giá trị (tự động)Rỗng có ý định (gán thủ công)
LoạiPrimitivePrimitive
typeof"undefined""object" (bug lịch sử)
==undefined == null // true
===undefined === null // false

Kiểm tra undefined an toàn

// Cách 1: So sánh trực tiếp (khuyến nghị)
if (variable === undefined) { ... }

// Cách 2: typeof (an toàn nếu biến chưa khai báo)
if (typeof variable === 'undefined') { ... }

// Cách 3: Kiểm tra truthy/falsy (cẩn thận: false, 0, '', null cũng falsy)
if (!variable) { ... } // true cho undefined, null, 0, '', false

// Cách 4: Optional chaining (ES2020) - cho property
const value = obj?.prop?.nested; // undefined nếu bất kỳ cấp nào missing

Lưu ý quan trọng

  • undefined là **biến toàn cục** (property của globalThis), **không phải từ khóa**. Có thể ghi đè (tránh làm): undefined = 123.
  • Trong strict mode, gán cho undefined ném lỗi.
  • Dùng void 0 để lấy giá trị undefined chuẩn không thể ghi đè.