Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

Null Coalescing Operator (??) ใน JavaScript

Nullish Coalescing Operator (??) เป็น ES2020 feature คืนค่า Right-hand side ก็ต่อเมื่อ Left-hand side เป็น null หรือ undefined เท่านั้น (ไม่รวม falsy อื่นๆ เช่น 0, '', false)

ตัวอย่างจากบทความ (Logical OR - ไม่ใช่ Nullish Coalescing)

<html>
  <body>
    <script>
      var a = true;
      var b = false;
      document.write("(a || b) => ");
      result = (a || b);
      document.write(result); // true
    </script>
  </body>
</html>
⚠️ หมายเหตุ: บทความต้นฉบับอธิบาย || (Logical OR) ไม่ใช่ ?? (Nullish Coalescing) เนื้อหาข้างล่างคือคำอธิบายที่ถูกต้องของ ??

Nullish Coalescing (??) vs Logical OR (||)

Expression|| (Logical OR)?? (Nullish Coalescing)
null ?? 'default''default''default'
undefined ?? 'default''default''default'
'' ?? 'default''default''' (empty string)
0 ?? 'default''default'0 (zero)
false ?? 'default''default'false
NaN ?? 'default''default'NaN
'hello' ?? 'default''hello''hello'

ตัวอย่างการใช้งาน ??

1. Default Parameters (แทน ||)

function greet(name) {
  // ก่อน ES2020
  name = name || 'Guest'; // ปัญหา: name = '' จะกลายเป็น 'Guest'
  
  // ES2020 - ใช้ ??
  name = name ?? 'Guest'; // เฉพาะ null/undefined
  
  console.log(`Hello, ${name}!`);
}

greet('');     // "Hello, !" (ถูกต้อง - empty string เป็นค่าที่ตั้งใจ)
greet(null);   // "Hello, Guest!"
greet(undefined); // "Hello, Guest!"

2. Config Defaults

function connect(config = {}) {
  const host = config.host ?? 'localhost';
  const port = config.port ?? 3000;
  const secure = config.secure ?? false; // false เป็นค่าที่ตั้งใจได้!
  const timeout = config.timeout ?? 5000; // 0 เป็น valid timeout
  
  return { host, port, secure, timeout };
}

connect({ port: 0, secure: false, timeout: 0 });
// { host: 'localhost', port: 0, secure: false, timeout: 0 } ✓

connect({ port: 0, secure: false, timeout: 0 });
// ด้วย || จะได้ port: 3000, secure: false (OK), timeout: 5000 ❌

3. Chaining (Fallback Chain)

const value = 
  userInput ?? 
  config.default ?? 
  systemDefault ?? 
  'fallback';

4. กับ Optional Chaining (?.)

const userName = user?.profile?.name ?? 'Anonymous';
// user = null/undefined → 'Anonymous'
// user.profile = null/undefined → 'Anonymous'
// user.profile.name = '' → '' (empty string - ค่าที่ตั้งใจ!)

Browser Support

  • Chrome 80+, Firefox 72+, Safari 13.1+, Edge 80+
  • Node.js 14+
  • IE: ไม่รองรับ (ต้อง transpile)

สรุป

ใช้ ?? สำหรับ Default Values (เฉพาะ null/undefined)
ใช้ || สำหรับ Boolean Logic หรือ Truthy Fallback
ใช้ ?. (Optional Chaining) ร่วมกับ ?? สำหรับ Deep Access