How to check a not-defined variable in JavaScript

后端 未结 14 918
陌清茗
陌清茗 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:18

    Another potential "solution" is to use the window object. It avoids the reference error problem when in a browser.

    if (window.x) {
        alert('x exists and is truthy');
    } else {
        alert('x does not exist, or exists and is falsy');
    }
    

提交回复
热议问题