Detecting an undefined object property

后端 未结 30 3684
花落未央
花落未央 2020-11-21 04:43

What\'s the best way of checking if an object property in JavaScript is undefined?

30条回答
  •  萌比男神i
    2020-11-21 05:39

    I'm not sure where the origin of using === with typeof came from, and as a convention I see it used in many libraries, but the typeof operator returns a string literal, and we know that up front, so why would you also want to type check it too?

    typeof x;                      // some string literal "string", "object", "undefined"
    if (typeof x === "string") {   // === is redundant because we already know typeof returns a string literal
    if (typeof x == "string") {    // sufficient
    

提交回复
热议问题