Home > Article > Web Front-end > How to check whether a variable is defined in javascript
Javascript method to detect whether a variable is defined: 1. Use the typeof operator to obtain the data type of the variable, the syntax is "typeof variable name"; 2. Use the "===" operator to determine whether the obtained data type is "undefined" type, if yes, it is undefined, otherwise it is defined.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Undefined is also a special data type with only one value, indicating undefined. For undeclared variables, use the typeof operator to check their types and you will find that the undeclared variables are undefined:
So we can first use the typeof operator to get the JavaScript variable Data type, and then determine whether the obtained data type is of "undefined" type. If so, it is undefined, otherwise it is defined.
if ( typeof b == "undefined" ) { console.log("未定义"); } else{ console.log("定义"); }
Output:
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How to check whether a variable is defined in javascript. For more information, please follow other related articles on the PHP Chinese website!