Skip to main content

typeof in JavaScript

typeof in JavaScript

The typeof operator in JavaScript is a powerful tool for determining the type of a given value or variable. It returns a string indicating the type of the operand, which helps developers handle different data types effectively in their code.


Using the typeof Operator

The typeof operator is straightforward to use. Here's the basic syntax:

typeof operand;

The operand can be a variable, an object, a function, or any value you want to check. The result will be a string that represents the data type of the operand.


Examples of typeof

Let's explore some common examples to understand how typeof works:

1. Checking Primitive Types

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

Here, typeof returns the expected type for each primitive value. Note that null returns "object" due to a historical quirk in JavaScript.


2. Checking Reference Types

console.log(typeof {});         // "object"
console.log(typeof []);         // "object"
console.log(typeof function(){}); // "function"

In these examples, typeof identifies objects, arrays, and functions. Arrays return "object" because they are a type of object in JavaScript.


3. Special Cases

There are a few special cases to be aware of:

console.log(typeof NaN);      // "number"
console.log(typeof Infinity); // "number"
console.log(typeof null);      // "object"

Although NaN (Not-a-Number) and Infinity are special values, typeof identifies them as "number". null is an "object" due to legacy reasons.


Common Use Cases for typeof

Here are some scenarios where typeof is particularly useful:

  • Type Checking: Ensure that a variable has the expected type before performing operations on it.
  • Conditional Logic: Use typeof in conditional statements to handle different types differently.
  • Debugging: Quickly identify the type of a value during debugging to understand unexpected behavior.

Conclusion

The typeof operator is a simple yet essential tool in JavaScript, allowing developers to check the type of any value or variable. Understanding its behavior and quirks, such as the "object" return value for null, is important for writing robust and error-free code.

Comments