A typeof keyword returns a string indicating the Data Type of the identifier. We use it for getting the type of primitive values.
The syntax of the Typeof is as shown below. It returns the data type of the identifier, which we place right next to it.
typeof identifier
typeof (identifier)
For Example
var str="hello world"
console.log(typeof str) //string
Typeof correctly returns the type in case of number, string, boolean, symbol, undefined, function. Everything else is object. That also includes null.
console.log(typeof 1337) // number
console.log(typeof NaN) // number
console.log(typeof Infinity) // number
console.log(typeof Number('1')) // number
console.log(typeof 512n)) // bigint
console.log(typeof "foo") // string
console.log(typeof true) // boolean
console.log(typeof {}) // object
console.log(typeof Math.round) // function
console.log(typeof Symbol()) // symbol
console.log(typeof undefined) // undefined
console.log(typeof null) // object
console.log(typeof [1, 2, 3]) // object
console.log(typeof Math) // object
console.log(typeof new Boolean(true)) // object
console.log(typeof new Number(10)) // object
console.log(typeof new String('xyz')) // object
The following table summarizes the possible return values of typeof.
| Type | Result |
|---|---|
| Undefined | “undefined” |
| Null | “object” |
| Boolean | “boolean” |
| Number | “number” |
| BigInt | “bigint” |
| String | “string” |
| Symbol | “symbol” |
| Function object | “function” |
| Everything Else | “object” |
Although the null is a data type in JavaScript, typeof null returns “object”
console.log(typeof null) // object
In the first implementation of JavaScript, JavaScript values were represented as a type tag and a value. The type tag for objects was 0. null was represented as the NULL pointer (0x00 in most platforms). Consequently, null had 0 as type tag, hence the typeof return value “object”
A fix was proposed for ECMAScript (via an opt-in), but was rejected. It would have resulted in typeof null === ‘null’.