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

Logical Operators ใน JavaScript คืออะไร?

JavaScript รองรับ logical operators ต่อไปนี้ สมมติตัวแปร A = 10 และ B = 20:

ลำดับOperator และ คำอธิบาย
1&& (Logical AND)
ถ้าทั้งสอง operand เป็น non-zero (truthy) เงื่อนไขเป็น true
Ex: (A && B) is true.
2|| (Logical OR)
ถ้า operand ใด operand หนึ่งเป็น non-zero (truthy) เงื่อนไขเป็น true
Ex: (A || B) is true.
3! (Logical NOT)
กลับสถานะ logical ของ operand ถ้าเงื่อนไข true จะกลายเป็น false
Ex: !(A && B) is false.

ตัวอย่าง

<html> 
  <body> 
    <script> 
      var a = true; 
      var b = false; 
      var linebreak = "<br />"; 
      document.write("(a && b) => "); 
      result = (a && b); 
      document.write(result); 
      document.write(linebreak); 
      document.write("(a || b) => "); 
      result = (a || b); 
      document.write(result); 
      document.write(linebreak); 
      document.write("!(a && b) => "); 
      result = (!(a && b)); 
      document.write(result); 
    </script> 
    <p>Set the variables to different values and different operators and then try...</p> 
  </body> 
</html>

Short-Circuit Evaluation (การประเมินแบบลัดวงจร)

  • &&: ถ้า operand แรกเป็น falsy → คืนค่า operand แรกทันที (ไม่ประเมินตัวที่สอง)
  • ||: ถ้า operand แรกเป็น truthy → คืนค่า operand แรกทันที (ไม่ประเมินตัวที่สอง)
  • ใช้ได้สำหรับ default values: const name = userName || "Guest"

Nullish Coalescing (ES2020) — ??

เหมือน || แต่ตรวจสอบเฉพาะ null/undefined (ไม่ใช่ falsy อื่นๆ)

const count = 0;
count || 10;    // 10 (เพราะ 0 เป็น falsy)
count ?? 10;    // 0 (เพราะ 0 ไม่ใช่ null/undefined)