Skip to main content
Back to index

JavaScript / Easy

Detect Type

Build a helper that returns a precise lowercase type name for a JavaScript value. The goal is to avoid the common blind spots in `typeof` while keeping the function small and predictable.

Problem

Implement detectType(value). It should return labels such as string, number, null,array, date, map, andset.

Edge Cases

  • `typeof null` returns `"object"`.
  • Arrays also return `"object"` with `typeof`.
  • Boxed primitives like `new String("x")` should be distinguishable from plain strings.
  • Built-ins such as `Date`, `RegExp`, `Map`, and `Set` need clearer labels.

Implementation

function detectType(value) {
  if (value === null) {
    return "null"
  }

  const primitiveType = typeof value

  if (primitiveType !== "object") {
    return primitiveType
  }

  return Object.prototype.toString
    .call(value)
    .slice(8, -1)
    .toLowerCase()
}

Examples

detectType(null)"null"
detectType([])"array"
detectType(new Date())"date"
detectType(new Map())"map"
detectType(() => {})"function"

Reasoning

Primitives are fastest to classify with typeof. For objects, Object.prototype.toString.call(value) exposes the internal built-in tag, which gives reliable names for arrays and common object types without maintaining a long manual list.

© 2026 Krisna Wijaya