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
coldplay.xixiOriginal
2021-04-09 16:51:215063browse

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)
if ( callbackfun != "undefined" ) {
    callbackfun();
}
//发现判断不出来,最后查了下资料要用typeof
//方法:
if ( typeof(callbackfun) != "undefined" ) {
    callbackfun();
}

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!

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