Using typeof vs === to check undeclared variable produces different result

前端 未结 6 939
闹比i
闹比i 2020-12-20 19:39

If I have an undeclared variable and use typeof it tells me it\'s undefined. But if I then check it using if (qweasdasd === undefined)

相关标签:
6条回答
  • 2020-12-20 19:51

    You have an undefined variable, but not an undefined object value.

    console.log(variable) // undefined
    console.log(typeof variable) // "undefined"
    console.log(variable === undefined) // Reference error
    variable = undefined ; 
    console.log(variable === undefined) // true
    
    0 讨论(0)
  • 2020-12-20 19:55

    typeof is an operator that returns you a string indicating the type of the unevaluated operand. It doesn't matter if the unevaluated operand is undefined or not. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof

    >>> if (a !== 'undefined');
    Exception: ReferenceError: Can't find variable: a
    >>> if (typeof a !== undefined);
    undefined
    >>> if (typeof a !== void 0);
    undefined
    
    0 讨论(0)
  • 2020-12-20 19:59

    Trying to access undefined variable in Javascript gives ReferenceError. typeof is working because it not accessing variable value. Its checking its type.

    typeof not requires defined variable. Its parameter should be an expression representing the object or primitive whose type is to be returned.

    0 讨论(0)
  • 2020-12-20 20:00

    Trying to read the value of an undeclared variable (which you have to do before you can compare that value to the value of undefined) throws a ReferenceError.

    Applying the typeof operator to an undeclared variable does not.

    0 讨论(0)
  • 2020-12-20 20:04

    I think I have a very simple explanation for this -- because the specs say so:

    • typeof operator is not supposed to throw the ReferenceError exception if the variable is not defined
    1. If Type(val) is Reference, then
      a. If IsUnresolvableReference(val) is true, return "undefined".
    • === operator is supposed to throw the ReferenceError exception if the operand(s) refer to undefined variables
    1. Let lval be GetValue(lref).

    [And inside the definition of GetValue we have]

    1. Let base be the result of calling GetBase(V).
    2. If IsUnresolvableReference(V), throw a ReferenceError exception.
    0 讨论(0)
  • 2020-12-20 20:05

    typeof looks like a function call, but it is not - it is an operator. Operators are allowed to break rules. typeof(qweasdasd) does not assume qweasdasd exists; whether it exists or not and what it is is what typeof exists to discover. However, when you test qweasdasd === undefined, you are using qweasdasd as a value, and JS complains when you use a variable that you haven't assigned a value to.

    0 讨论(0)
提交回复
热议问题