Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

JavaScript typeof, null, and undefined

JavaScript typeof, null, and undefined


The typeof operator

You can use the typeof operator to check 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 »

| 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
| | --- | --- |

typeof is 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" Symbol type added in ES6
typeof BigInt(10) "bigint" BigInt type added in ES2020

Detecting an undefined variable:



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

Detecting whether a function exists:



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

Note the special cases of array and null:



// Correctly check array

if (Array.isArray(myVar)) {...}



// Correctly check for 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 Checking null with typeof returns object.

You can set it to null to empty an object:

Example

var

person =

null

;          

// the value is null (empty), but the type is object

Try it »

You can set it to undefined to empty an object:

Example

var

person = undefined;    

// the value is undefined, the type is undefined

Try it »


undefined

In JavaScript, undefined is a variable that has not been assigned a value.

typeof A variable with no value will return ** undefined**.

Example

var

person;                 

// the value is undefined (empty), the type is undefined

Try it »

Any variable can be emptied by setting its value to undefined . The type is undefined.

Example

person = undefined;         

// the value is undefined, the type is undefined

Try it »


The difference between undefined and null

Example

The values of null and undefined are equal, but their types are not:

typeof

undefined            

// undefined

typeof

null

                 

// object

null

=== undefined          

// false

null

== undefined           

// true

Try it »