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

Logical OR Operator (||) ใน JavaScript

Logical OR (||) คืนค่า true ก็ต่อเมื่อ อย่างน้อยหนึ่ง operand เป็น truthy มิฉะนั้นคืนค่า operand ตัวสุดท้าย (Short-circuit evaluation)

ตัวอย่างจากบทความ

<html>
  <body>
    <script>
      var a = true;
      var b = false;
      document.write("(a || b) => ");
      result = (a || b);
      document.write(result); // true
    </script>
  </body>
</html>

Truth Table

ABA || B
truetruetrue
truefalsetrue
falsetruetrue
falsefalsefalse

Short-Circuit Evaluation

|| จะหยุดประเมินทันที เมื่อเจอ truthy value แรก

true || false;    // true (หยุดที่ true)
false || true;    // true (หยุดที่ true)
false || false;   // false (ประเมินทั้งคู่)
true || true;     // true (หยุดที่ true แรก)

คืนค่า Operand จริง (ไม่ใช่แค่ true/false)

// คืนค่า operand แรกที่เป็น truthy
0 || 5;           // 5
"" || "hello";    // "hello"
null || "world";  // "world"
undefined || 1;   // 1

// คืนค่า operand ตัวสุดท้ายถ้าทั้งคู่ falsy
0 || "";          // ""
null || undefined; // undefined
false || 0;       // 0

การใช้งานจริง (Practical Patterns)

1. Default Values (ก่อน ES6 Nullish Coalescing)

function greet(name) {
  name = name || 'Guest'; // name falsy → 'Guest'
  // ⚠️ ปัญหา: name = '', 0, false จะกลายเป็น 'Guest'
}

function greetBetter(name) {
  name = name !== undefined && name !== null ? name : 'Guest';
  // หรือ ES2020:
  name = name ?? 'Guest'; // เฉพาะ null/undefined
}

2. Fallback Chain

const config = userConfig || defaultConfig || globalConfig || {};

// API call with fallback
const data = await fetchPrimary() || await fetchSecondary() || getDefaultData();

3. Lazy Initialization

let instance;
function getInstance() {
  return instance || (instance = new HeavyClass());
}

4. Feature Detection

const hasLocalStorage = window.localStorage || false;
const requestAnimationFrame = window.requestAnimationFrame || 
                              window.webkitRequestAnimationFrame || 
                              fallback;

Nullish Coalescing (??) vs || (ES2020)

Expression||??
null || 'default''default''default'
undefined || 'default''default''default'
'' || 'default''default'''
0 || 'default''default'0
false || 'default''default'false
แนะนำ: ใช้ ?? สำหรับ default values (เฉพาะ null/undefined) ใช้ || สำหรับ boolean logic หรือ truthy fallback

Operator Precedence

|| ต่ำกว่า &&

a && b || c   // (a && b) || c
a || b && c   // a || (b && c)