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

ตัวดำเนินการ ! (Exclamation/Logical NOT) ใน JavaScript

ตัวดำเนินการ ! (Logical NOT) ใช้ทำ Negation (ลบ) บนนิพจน์ แปลงค่าเป็น Boolean แล้วกลับค่า

ตัวอย่าง

<html>
  <head>
    <title>JavaScript Boolean</title>
  </head>
  <body>
    <script>
      var answer = true;
      document.write(answer);        // true
      document.write("<br>" + !answer); // false
    </script>
  </body>
</html>

ตารางความจริง (Truth Table)

x!x
truefalse
falsetrue

การทำงานกับค่าอื่น (Type Coercion)

! จะแปลง operand เป็น Boolean ก่อน (ToBoolean) แล้วค่อยกลับค่า:

ValueBoolean(x)!x
truetruefalse
falsefalsetrue
0falsetrue
1truefalse
""falsetrue
"hello"truefalse
nullfalsetrue
undefinedfalsetrue
NaNfalsetrue
{}truefalse
[]truefalse

Double Negation (!!)

ใช้แปลงค่าใดๆ ให้เป็น Boolean จริง (primitive):

!!"hello"  // true
!!0        // false
!!null     // false
!!{}       // true
// เทียบเท่า Boolean(value)

การใช้งานทั่วไป

  • if (!value) – ตรวจสอบ falsy
  • !!value – normalize เป็น boolean
  • !isValid – กลับเงื่อนไข