JavaScript

This page explains how the typeof operator reports the type of a value at runtime.

Goal: use typeof to inspect values and understand its important exceptions for null, arrays, functions, and undeclared names.

The typeof operator

typeof returns a string describing the type of its operand. It is useful when a function accepts values of different kinds or when you are debugging a condition.

JavaScript

typeof 42;            // "number"
typeof "hello";       // "string"
typeof true;          // "boolean"
typeof undefined;     // "undefined"
typeof null;          // "object"
typeof {};            // "object"
typeof function () {}; // "function"

Check a function argument

JavaScript

function greet(name) {
  if (typeof name === "string") {
    return "Hello, " + name + "!";
  }
  return "Please provide a name.";
}

greet("Alice"); // Hello, Alice!
greet(42);      // Please provide a name.

Important exceptions

Related topics