Short-circuit Evaluation** คือพฤติกรรมของ Logical Operators (&& และ ||) ที่ประเมินค่าจากซ้ายไปขวา และหยุดทันทีเมื่อผลลัพธ์สามารถกำหนดได้แล้ว
หลักการทำงาน
| Operator | ชื่อ | หยุดเมื่อเจอ | คืนค่า |
|---|---|---|---|
&& | Logical AND | Falsy แรก | ค่า Falsy นั้น (หรือค่าสุดท้ายถ้าทุกค่า Truthy) |
|| | Logical OR | Truthy แรก | ค่า Truthy นั้น (หรือค่าสุดท้ายถ้าทุกค่า Falsy) |
ตัวอย่างโค้ด
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Short-circuit Evaluation</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.result { font-size: 20px; font-weight: 500; color: blueviolet; }
</style>
</head>
<body>
<h1>Short-circuit Evaluation</h1>
<div class="result"></div>
<br />
<button class="Btn">&& Short Circuit</button>
<button class="Btn">|| Short Circuit</button>
<h3>คลิกปุ่มด้านบนเพื่อดู Short Circuit Evaluation</h3>
<script>
const resEle = document.querySelector(".result");
const BtnEle = document.querySelectorAll(".Btn");
function retTrue() {
resEle.innerHTML += "True <br>";
return true;
}
function retFalse() {
resEle.innerHTML += "False <br>";
return false;
}
BtnEle[0].addEventListener("click", () => {
resEle.innerHTML = "&& evaluation<br>";
retFalse() && retTrue(); // retTrue() ไม่ถูกเรียก
});
BtnEle[1].addEventListener("click", () => {
resEle.innerHTML = "|| evaluation <br>";
retTrue() || retFalse(); // retFalse() ไม่ถูกเรียก
});
</script>
</body>
</html>
การประยุกต์ใช้จริง
// 1. Default Parameter (ก่อน ES6)
function greet(name) {
name = name || "Guest"; // หรือ name ?? "Guest" (ES2020)
}
// 2. Guard Clause - ป้องกัน Error
const user = getUser();
const name = user && user.profile && user.profile.name;
// 3. Conditional Execution
isLoggedIn && renderDashboard(); // render ก็ต่อเมื่อ login
// 4. Cache/Memoization
const cache = {};
function getData(key) {
return cache[key] || (cache[key] = expensiveOperation(key));
}
ผลลัพธ์
- ปุ่ม
&&: แสดง "False" เท่านั้น - ปุ่ม
||: แสดง "True" เท่านั้น