JavaScript - typeof

In JavaScript, the typeof operator is used to determine the type of a given variable or expression. It’s particularly useful in debugging and in conditions where you need to handle data of various types differently. This post covers the basics of the typeof operator, along with some examples and caveats.

What is the typeof Operator?

The typeof operator returns a string that represents the type of the variable or expression you pass to it. It can be used with both primitive data types and objects, providing a quick way to check the type of a variable.

 

Syntax

typeof operand

Here, operand is the variable or expression whose type you want to check.

Example

let name = "Alice";

console.log(typeof name); // Output: "string"

Note: The typeof null returns "object", which is considered a historical quirk in JavaScript.

Using typeof with Different Data Types

Primitive Data Types

String:

let str = "JavaScript";

console.log(typeof str); // "string"

Number:

let num = 42;

console.log(typeof num); // "number"

Boolean:

let isValid = true;

console.log(typeof isValid); // "boolean"

BigInt:

let bigIntVal = 9007199254740991n;

console.log(typeof bigIntVal); // "bigint"

Symbol:

let sym = Symbol("identifier");

console.log(typeof sym); // "symbol"

Undefined:

let notDefined;

console.log(typeof notDefined); // "undefined"

Special Case: null

As mentioned, typeof null returns "object". This is a historical bug in JavaScript and has remained for compatibility reasons.

let empty = null;

console.log(typeof empty); // "object"

Functions

Functions return "function" when checked with typeof, making it easy to detect them.

function greet() {

  return "Hello!";

}

console.log(typeof greet); // "function"

Arrays and Objects

JavaScript arrays and objects both return "object" when checked with typeof, so you may need to use other checks to differentiate them if necessary.

let myArray = [1, 2, 3];

console.log(typeof myArray); // "object"

let myObject = {name: "Alice"};

console.log(typeof myObject); // "object"

To check specifically if a variable is an array, you can use Array.isArray():

console.log(Array.isArray(myArray)); // true

console.log(Array.isArray(myObject)); // false

Practical Uses of typeof

1. Checking for Undefined Variables

typeof is helpful when you want to check if a variable is undefined without causing an error.

let unknown;

if (typeof unknown === "undefined") {

  console.log("Variable is undefined");

}

2. Detecting Types for Conditional Logic

Sometimes you need to handle data differently depending on its type.

function processData(value) {

  if (typeof value === "string") {

    console.log("Processing a string:", value);

  } else if (typeof value === "number") {

    console.log("Processing a number:", value);

  } else {

    console.log("Unknown data type");

  }

}

processData(100);      // Processing a number: 100

processData("Hello");  // Processing a string: Hello

3. Validating Function Parameters

In JavaScript, function parameters are loosely typed, so typeof can help ensure the correct type is passed in.

function add(a, b) {

  if (typeof a !== "number" || typeof b !== "number") {

    throw new Error("Both parameters must be numbers");

  }

  return a + b;

}

console.log(add(5, 10)); // 15

console.log(add("5", 10)); // Error: Both parameters must be numbers

Limitations and Caveats of typeof

Array Detection: Arrays are objects in JavaScript, so typeof [] returns "object". Use Array.isArray() for a precise check.

null Detection: typeof null returns "object", which is a known quirk.

Distinguishing Objects: All objects, arrays, and other complex data structures will return "object", so further inspection may be necessary.

Conclusion

The typeof operator is a powerful and easy-to-use tool in JavaScript that helps you determine the type of a variable quickly. Although there are some quirks, understanding how typeof works will allow you to write cleaner, more error-resistant code. Use typeof to handle different data types effectively, check undefined variables, and validate function parameters.