JS typeof Operator

JavaScript typeof Operator

In JavaScript, the typeof operator returns a string indicating the data type of the unevaluated operand. It is an incredibly useful tool for type-checking and debugging.

Syntax

typeof operand
// or
typeof(operand)

typeof Return Values

The typeof operator can return one of the following strings:

Data Type String Returned by typeof
String "string"
Number "number"
BigInt "bigint"
Boolean "boolean"
Symbol "symbol"
Undefined "undefined"
Object "object"
Function "function"

typeof Examples

console.log(typeof "Hello");      // "string"
console.log(typeof 42);           // "number"
console.log(typeof true);         // "boolean"
console.log(typeof undefined);    // "undefined"
console.log(typeof 123n);         // "bigint"
console.log(typeof Symbol('id')); // "symbol"

The typeof Operator and Objects

It's important to note that typeof returns "object" for all object types, including arrays, dates, and regular expressions. It does not differentiate between them.

typeof with Objects

console.log(typeof {name: "John"}); // "object"
console.log(typeof [1, 2, 3]);      // "object"
console.log(typeof new Date());     // "object"

The typeof null Bug

One of the most famous quirks in JavaScript is that typeof null returns "object".

Historical Bug: This is a well-known bug from the earliest days of JavaScript. For backward compatibility, it has never been fixed. You should remember that null is a primitive value, not an object, despite what typeof says.

The typeof null Bug

let data = null;
console.log(typeof data); // "object"

To correctly check if a value is an object (and not null), you should use: value !== null && typeof value === 'object'


Exercise

?

What does `typeof [1, 2, 3]` return?