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

How to check whether a variable is defined in javascript

青灯夜游
Release: 2021-11-04 14:50:40
Original
5970 people have browsed it

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("定义");
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template