ตัวแปร Boolean ใน JavaScript มีค่าสองค่า คือ True หรือ False
ตัวอย่าง
ลองรันโค้ดต่อไปนี้เพื่อเรียนรู้การทำงานกับตัวแปร Boolean:
<!DOCTYPE html>
<html>
<body>
<p>35 > 20</p>
<button onclick="myValue()">Click for result</button>
<p id="test"></p>
<script>
function myValue() {
document.getElementById("test").innerHTML = Boolean(35 > 20);
}
</script>
</body>
</html>
วิธีประกาศ Boolean
- Literal:
true/false(แนะนำ) - Constructor:
new Boolean(value)— สร้างออบเจกต์ ไม่แนะนำสำหรับการใช้งานทั่วไป - Function:
Boolean(value)— แปลงค่าเป็น primitive boolean
ค่าที่เป็น falsy (แปลงเป็น false): false, 0, -0, 0n, "", null, undefined, NaN — ส่วนที่เหลือเป็น truthy