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

How to determine whether a variable is defined in javascript

coldplay.xixi
Release: 2023-01-04 09:35:52
Original
5066 people have browsed it

Javascript method to determine whether a variable is defined: the object may be null only if it is defined, otherwise it is undefined. Use typeof to detect whether the object has been defined. The code is [if (typeof myObj !== "undefined" && myObj !].

How to determine whether a variable is defined in javascript

##The operating environment of this tutorial: windows7 system, javascript version 1.8.5, DELL G3 computer.

javascript Method to determine whether a variable is defined:

In JavaScript, null is used for objects, and undefined is used for variables, properties and methods.

Objects can only be null if they are defined. Otherwise, it is undefined.

If we want to test whether the object exists, an error will be thrown when the object has not been defined.

The correct way is that we need to use typeof first to detect whether the object Defined:

if (typeof myObj !== "undefined" && myObj !== null)
Copy after login
if ( callbackfun != "undefined" ) {
    callbackfun();
}
//发现判断不出来,最后查了下资料要用typeof
//方法:
if ( typeof(callbackfun) != "undefined" ) {
    callbackfun();
}
Copy after login

Related free learning recommendations:

javascript (video)

The above is the detailed content of How to determine 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