Detecting an undefined object property

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

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

30条回答
  •  广开言路
    2020-11-21 05:26

    I believe there are a number of incorrect answers to this topic. Contrary to common belief, "undefined" is not a keyword in JavaScript and can in fact have a value assigned to it.

    Correct Code

    The most robust way to perform this test is:

    if (typeof myVar === "undefined")
    

    This will always return the correct result, and even handles the situation where myVar is not declared.

    Degenerate code. DO NOT USE.

    var undefined = false;  // Shockingly, this is completely legal!
    if (myVar === undefined) {
        alert("You have been misled. Run away!");
    }
    

    Additionally, myVar === undefined will raise an error in the situation where myVar is undeclared.

提交回复
热议问题