Home  >  Article  >  Web Front-end  >  Knowledge about JavaScript typeof, null, and undefined

Knowledge about JavaScript typeof, null, and undefined

jacklove
jackloveOriginal
2018-05-07 10:13:351712browse

JavaScript typeof, null, and undefined operators play a very important role in js. Let us explain them in detail.

typeof operator

You can use the typeof operator to detect the data type of a variable.

Example

typeof "John"                // 返回 string 
typeof 3.14                  // 返回 number
typeof false                 // 返回 boolean
typeof [1,2,3,4]             // 返回 object
typeof {name:'John', age:34} // 返回 object

In JavaScript, an array is a special object type. So typeof [1,2,3,4] returns object.​

null

In JavaScript, null means "nothing".

null is a special type with only one value. Represents an empty object reference.

#Use typeof to detect null and return object.

You can set it to null to clear the object:

Instance

var person = null;           // 值为 null(空), 但类型为对象

You can set it to undefined to clear the object:

Instance

var person = undefined;     // 值为 undefined, 类型为 undefined

undefined

In JavaScript, undefined is a variable that has no set value.

typeof A variable with no value will return undefined.

Example

var person;                  // 值为 undefined(空), 类型是undefined

Any variable can be cleared by setting the value to undefined. The type is undefined.

Instance

person = undefined;          // 值为 undefined, 类型是undefined

The difference between undefined and null

Instance

The values ​​of null and undefined are equal, but the types are not the same:

typeof undefined             // undefined
typeof null                  // object
null === undefined           // false
null == undefined            // true

This article explains in detail the knowledge related to JavaScript typeof, null, and undefined. For more learning materials, please pay attention to the php Chinese website.

Related recommendations:

JavaScript Date (date) related knowledge and usage

Introduction to the use of JavaScript RegExp objects

About how to use JavaScript Array (array) object

The above is the detailed content of Knowledge about JavaScript typeof, null, and undefined. 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