Home  >  Article  >  Web Front-end  >  How to check whether a variable is defined in javascript

How to check whether a variable is defined in javascript

青灯夜游
青灯夜游Original
2021-11-04 14:50:405953browse

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.

How to check whether a variable is defined in javascript

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:

How to check whether a variable is defined in javascript

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:

How to check whether a variable is defined in javascript

[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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn