How to determine whether a value is undefined in javascript

青灯夜游
Release: 2022-02-08 11:20:55
Original
40745 people have browsed it

In JavaScript, you can use the typeof operator and the "==" operator to determine whether the specified value is undefined. The syntax "if (typeof (specified value) == "undefined"){//The value is undefined;}".

How to determine whether a value is undefined in javascript

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

Undefined type

Undefined is a special data type with only one value, which means undefined. When we declare a variable but do not assign a value to the variable, the default value of the variable is Undefined. For example:

var num;
console.log(num);  // 输出 undefined
Copy after login

So how to determine whether the value is undefined?

In JavaScript, you can use the typeof operator to determine whether the value is undefined.

When you use the typeof operator to view unassigned variable types, you will find that their types are also undefined. For undeclared variables, use the typeof operator to check their types and you will find that undeclared variables are also undefined. The sample code is as follows:

var message;
console.log(typeof message);  // 输出 undefined
console.log(typeof name);     // 输出 undefined
Copy after login

Judgment method:

var tmp = undefined;
if (typeof(tmp) == "undefined"){
alert("值为 undefined");
}
Copy after login

How to determine whether a value is undefined in javascript

Description: typeof operator

typeof is a unary operator used to return a string of the operand type.

  • The data type of NaN is number

  • The data type of array (Array) is object

  • The data type of date (Date) is object

  • The data type of null is object

  • The data type of undefined variables is undefined

typeof [1, 2, 3, 5];  // 返回object
typeof new Date();  // 返回 object
typeof NaN;  // 返回 number
typeof function () {}     // 返回 function
typeof myCar;     // 返回 undefined (如果 myCar 没有声明)
Copy after login

The difference between undefined and null:

typeof null;  // 返回object
typeof undefined;  // 返回undefined
null === undefined;  //false
null == undefined;  // true
Copy after login

[Related recommendations: javascript learning tutorial]

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