JavaScript checking for null vs. undefined and difference between == and ===

前端 未结 8 703
忘了有多久
忘了有多久 2020-11-22 16:53
  1. How do I check a variable if it\'s null or undefined and what is the difference between the null and undefined?<

8条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 17:26

    The spec is the place to go for full answers to these questions. Here's a summary:

    1. For a variable x, you can:

      • check whether it's null by direct comparison using ===. Example: x === null
      • check whether it's undefined by either of two basic methods: direct comparison with undefined or typeof. For various reasons, I prefer typeof x === "undefined".
      • check whether it's one of null and undefined by using == and relying on the slightly arcane type coercion rules that mean x == null does exactly what you want.

    2. The basic difference between == and === is that if the operands are of different types, === will always return false while == will convert one or both operands into the same type using rules that lead to some slightly unintuitive behaviour. If the operands are of the same type (e.g. both are strings, such as in the typeof comparison above), == and === will behave exactly the same.

    More reading:

    • Angus Croll's Truth, Equality and JavaScript
    • Andrea Giammarchi's JavaScript Coercion Demystified
    • comp.lang.javascript FAQs: JavaScript Type-Conversion

提交回复
热议问题