JavaScript Typeof

What is the typeof Operator?

The typeof operator in JavaScript returns a string that indicates the type of a given variable or expression. It is particularly useful for understanding the kind of data stored in a variable.

Syntax:

typeof operand
// OR
typeof(operand)
  • The operand can be a variable, literal, or expression.
  • The parentheses are optional and do not affect the behavior.

Examples of typeof

Here are examples of how the typeof operator works with various data types:

1. Primitive Data Types

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

2. Complex Data Types

console.log(typeof {});              // Output: "object" (for objects)
console.log(typeof []); // Output: "object" (arrays are objects)
console.log(typeof function() {}); // Output: "function" (functions are callable objects)

typeof Results for Data Types

The typeof operator returns the following results based on the data type:

Data TypeExampletypeof Result
Number42“number”
String‘Hello’“string”
Booleantrue“boolean”
Undefinedundefined“undefined”
Nullnull“object” (quirk)
SymbolSymbol(‘id’)“symbol”
Object{ key: ‘value’ }“object”
Array[1, 2, 3]“object”
Functionfunction() {}“function”

Common Use Cases of typeof

1. Checking Variable Type

const age = 25;
if (typeof age === 'number') {
console.log('Age is a number');
}
// Output: Age is a number

2. Handling Undefined Variables

let user;
if (typeof user === 'undefined') {
console.log('User is not defined');
}
// Output: User is not defined

3. Debugging with typeof

function calculate(num1, num2) {
if (typeof num1 !== 'number' || typeof num2 !== 'number') {
throw new Error('Both arguments must be numbers');
}
return num1 + num2;
}

console.log(calculate(10, 20)); // Output: 30
console.log(calculate(10, '20')); // Error: Both arguments must be numbers

Special Cases of typeof

1. null Returning “object”

The typeof null result is “object”, which is a long-standing JavaScript quirk. To accurately check for null, use strict equality:

let value = null;
console.log(typeof value); // Output: "object"
console.log(value === null); // Output: true

2. Arrays are Objects

The typeof operator returns “object” for arrays, but you can distinguish them using Array.isArray():

let arr = [1, 2, 3];
console.log(typeof arr); // Output: "object"
console.log(Array.isArray(arr)); // Output: true

3. Functions as “function”

The typeof operator uniquely identifies functions:

function greet() {
return 'Hello!';
}
console.log(typeof greet); // Output: "function"

Using typeof with Expressions

The typeof operator can evaluate expressions directly:

console.log(typeof (10 + 5));      // Output: "number"
console.log(typeof ('A' + 'B')); // Output: "string"
console.log(typeof (5 > 2)); // Output: "boolean"

Combining typeof with Conditional Statements

The typeof operator is often used in conditional logic to create robust and error-free code.

Example: Type-Based Operations

function processInput(input) {
if (typeof input === 'string') {
console.log('Input is a string:', input.toUpperCase());
} else if (typeof input === 'number') {
console.log('Input is a number:', input * 2);
} else {
console.log('Unsupported type:', typeof input);
}
}

processInput('hello'); // Output: Input is a string: HELLO
processInput(10); // Output: Input is a number: 20
processInput(true); // Output: Unsupported type: boolean

Advantages of Using typeof

  1. Dynamic Type Checking: Easily identify variable types at runtime.
  2. Improved Debugging: Helps catch type-related bugs early in development.
  3. Versatile: Works with both primitive and complex data types.
  4. Error Prevention: Prevents incorrect operations on incompatible data types.

Limitations of typeof

  1. null Quirk: Returns “object” for null, which can be misleading.
  2. Limited Array Detection: Cannot directly distinguish arrays from objects.
  3. Does Not Identify Subtypes: For example, typeof cannot differentiate between integer and float numbers.

Leave a Comment