JavaScript typeof, null, and undefined
The 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
| | In JavaScript, arrays are a special type of object. Therefore typeof [1,2,3,4] returns object. | | --- | --- |
null
In JavaScript, null represents "nothing".
null is a special type with only one value. It represents an empty object reference.
| | Using typeof to check null returns object. | | --- | --- |
You can set an object to null to empty it:
Example
var person = null; // Value is null, but type is object
You can set an object to undefined to empty it:
Example
var person = undefined; // Value is undefined, type is undefined
undefined
In JavaScript, undefined is a variable that has not been assigned a value.
typeof a variable without a value returns undefined.
Example
var person; // Value is undefined, type is undefined
Any variable can be emptied by setting its value to undefined. The type will be undefined.
Example
person = undefined; // Value is undefined, type is undefined
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