How to check a not-defined variable in JavaScript

后端 未结 14 757
陌清茗
陌清茗 2020-11-22 14:23

I wanted to check whether the variable is defined or not. For example, the following throws a not-defined error

alert( x );

How can I cat

14条回答
  •  死守一世寂寞
    2020-11-22 15:14

    Technically, the proper solution is (I believe):

    typeof x === "undefined"
    

    You can sometimes get lazy and use

    x == null
    

    but that allows both an undefined variable x, and a variable x containing null, to return true.

提交回复
热议问题