JavaScript typeof, null, and undefined
typeof Operator
You can use the typeof operator to detect the data type of a variable.
Example
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 »
![]() |
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:
| Expression | Return value | Description |
|---|---|---|
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.
![]() |
Using typeof to detect null returns object. |
|---|
You can set it to null to clear the object:
You can set it to undefined to clear the object:
undefined
In JavaScript,undefinedis a variable without a set value.
typeofA variable without a value returns undefined。
Any variable can, by setting its value toundefinedbe cleared. The type isundefined.
The Difference Between undefined and null
Example
null and undefined have equal values, but different types:
typeof null // object
null === undefined // false
null == undefined // true
Try it Yourself »
