JavaScript Typeof, Null and Undefined
typeof Operator
You can use the typeof operator to detect the data type of a variable.
Example
typeof "John" // return string typeof 3.14 // return number typeof false // return boolean typeof [1,2,3,4] // return object typeof {name:'John', age:34} // return object
![]() | In JavaScript, an array is a special type of object. Therefore 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 an object. |
---|
You can set it to null to clear the object:
Example
var person = null; // The value is null (empty), but the type is an object
You can set it to undefined to clear the object:
Example
var person = undefined; // value is undefined, type is undefined
undefined
In JavaScript, undefined is a variable with no set value.
typeof a variable with no value will return undefined .
Example
var person; // value is undefined (empty), type is undefined
Any variable can be cleared by setting the value to undefined . The type is undefined .
Example
person = undefined; // value is undefined, type is undefined
The Difference Between undefined and null
Example
The values of null and undefined are equal, but the types are not equal:
typeof undefined // undefined typeof null // object null === undefined // false null == undefined // true