JavaScript typeof, null, and undefined


typeof Operator

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

Example

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

Try it Yourself »

Note

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

The correct way to detect an array:

Array.isArray([1,2,3]); // true
[1,2,3] instanceof Array; // true

typeofis an operator in JavaScript used to return the data type of a given variable.

Complete type detection table:

ExpressionReturn valueDescription
typeof undefined"undefined"Undefined value
typeof true"boolean"Boolean
typeof 42"number"All number types
typeof "text""string"String
typeof {a:1}"object"Object, array, null
typeof function(){}"function"Function
typeof Symbol()"symbol"ES6 added Symbol type
typeof BigInt(10)"bigint"ES2020 added BigInt type

Detecting undefined variables:

if (typeof variable === "undefined") {...}

Detecting whether a function exists:

if (typeof myFunction === "function") {...}

Note the special cases of arrays and null:

// 正确检测数组
if (Array.isArray(myVar)) {...}

// 正确检测null
if (myVar === null) {...}

null

In JavaScript, null means "nothing".

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

Note Using typeof to detect null returns object.

You can set it to null to clear the object:

Example

var person = null;           // value is null (empty), but type is object

Try it Yourself »

You can set it to undefined to clear the object:

Example

var person = undefined;     // value is undefined, type is undefined

Try it Yourself »


undefined

In JavaScript,undefinedis a variable without a set value.

typeofA variable without a value returns undefined。

Example

var person;                  // value is undefined (empty), type is undefined

Try it Yourself »

Any variable can, by setting its value toundefinedbe cleared. The type isundefined.

Example

person = undefined;          // value is undefined, type is undefined

Try it Yourself »


The Difference Between undefined and null

Example

null and undefined have equal values, but different types:

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

Try it Yourself »
Other extensions