HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript typeof Operator

The typeof operator is the most common way to check the data type of a JavaScript variable. It returns a string that tells you what kind of data the value is.


Typeof Return Values

Here is a complete list of what typeof returns for different values:

Data Type Return Value
String "string"
Number "number"
BigInt "bigint"
Boolean "boolean"
Undefined "undefined"
Function "function"
Object "object"
Null "object" (The "null bug")

Primitive vs. Complex Data

JavaScript has two categories of data. typeof can easily identify primitives but treats most complex data as objects.

1. Primitive Data

These are simple values: string, number, boolean, undefined, null.

typeof "Mim" // "string"
typeof 25    // "number"
typeof true  // "boolean"

2. Complex Data

These are objects and functions. Notice that arrays are technically objects.

typeof {name:'Mim'} // "object"
typeof [1, 2, 3]    // "object" (Arrays are objects!)
typeof new Date()   // "object"

How to Accurately Identify Arrays

Since typeof [] returns "object", you need a different way to check if a variable is an array:

let colors = ["Red", "Green"];

// Method 1: Array.isArray()
console.log(Array.isArray(colors)); // true

// Method 2: instanceof
console.log(colors instanceof Array); // true

The Null Bug

In JavaScript, typeof null returns 'object'. This is a famous bug from the very first version of JavaScript. It remains in the language today because fixing it would break millions of websites that rely on this behavior.

Tip: If you want to check if a value is null, use a direct comparison: if (myValue === null).

The constructor Property

The constructor property returns the constructor function for all JavaScript variables. This is a very reliable way to identify technical types:

"Mim".constructor       // returns function String()
(3.14).constructor      // returns function Number()
[1,2,3].constructor     // returns function Array()
{name:'Mim'}.constructor // returns function Object()

Key Points to Remember

  • typeof returns the data type as a string
  • It correctly identifies primitives (string, number, etc.)
  • It returns "object" for both arrays and null
  • To identify arrays, use Array.isArray()
  • The constructor property is a more specific way to find the data type