Home > Web Front-end > JS Tutorial > body text

How to detect whether a variable exists in javascript

青灯夜游
Release: 2021-10-25 14:32:57
Original
4002 people have browsed it

In JavaScript, you can detect whether a variable exists by judging whether the value of the variable is "null" or whether the data type is "undefined". The syntax is "if(typeof(a)=="undefined"||a ==null){//Does not exist}else{//Exists}".

How to detect whether a variable exists in javascript

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

In the actual development process, there will be scenarios to determine whether a variable exists.

You only need to use it to determine whether the value of the variable is null or whether the data type is undefined; if so, it does not exist.

The first thing that comes to mind is

if(a==undefined){
        console.log("a is undefined")
    }else{
        console.log("a is defiend")
    }
Copy after login

An error will be reported here, it may cause blocking, and it is not elegant enough

How to detect whether a variable exists in javascript

Solution:

<script type="text/javascript">
 
//	var a=&#39;xixi&#39;; 
 
	if(typeof(a) == "undefined" || a == null)
		alert("a is undefined");
	else
		alert("a is defined");
</script>
Copy after login

typeof is an operator used to view data types. There are two ways to use it:

typeof(表达式)
typeof 变量名
Copy after login

The first is to operate on expressions, and the second is to operate on variables.

The return type of the typeof operator is a string, and the values ​​include the following:

  • 'undefined' --Undefined variable or value

  • 'boolean' --A variable or value of Boolean type

  • 'string' --A variable or value of string type

  • 'number' -- a variable or value of numeric type

  • 'object' -- a variable or value of object type, or null (this is a legacy issue from js history, will null is treated as object type)

  • 'function' -- a variable or value of function type

Use if (typeof(a )=="undefined") can determine whether variable a is undefined.

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of How to detect whether a variable exists 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