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

Logical AND Operator (&&) ใน JavaScript

Logical AND (&&) คืนค่า true ก็ต่อเมื่อ ทั้งสอง operand เป็น truthy มิฉะนั้นคืนค่า operand แรกที่เป็น falsy (Short-circuit evaluation)

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

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

Truth Table

ABA && B
truetruetrue
truefalsefalse
falsetruefalse
falsefalsefalse

Short-Circuit Evaluation (สำคัญ!)

&& จะหยุดประเมินทันที เมื่อเจอ falsy value แรก (ไม่ประเมินตัวหลัง)

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

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

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

// คืนค่า operand ตัวสุดท้ายถ้าทั้งคู่ truthy
1 && 2;           // 2
"hello" && "world"; // "world"
{} && [];         // []

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

1. Conditional Execution (Guard Clause)

// แทน if (user) { user.save(); }
user && user.save();

// แทน if (config && config.api && config.api.url) { ... }
config && config.api && config.api.url && fetch(config.api.url);

2. Default Values (ก่อน ES6)

function greet(name) {
  name = name || 'Guest'; // name falsy → ใช้ 'Guest'
  // ปัญหา: name = '' หรือ 0 จะกลายเป็น 'Guest'
}

3. Optional Chaining Alternative (ก่อน ES2020)

// แทน user?.profile?.name
const name = user && user.profile && user.profile.name;

4. Render ใน React/JSX

{isLoggedIn && }
// แทน
{if (isLoggedIn) { return  }}

5. Lazy Initialization

let cache;
function getData() {
  return cache || (cache = expensiveComputation());
}

Operator Precedence

&& มี precedence สูงกว่า || แต่น้อยกว่า Comparison/Arithmetic

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

ข้อควรระวัง

  • ไม่ใช่ Boolean operator อย่างเดียว - คืนค่า operand จริง
  • Side effects ใน operand ตัวที่ 2 จะไม่รันถ้าตัวแรก falsy
  • [] && {} = {} (ทั้งคู่ truthy)