Facebook Pixel

Detect data type in JS

JavaScript
medium
20 mins

You are required to write a function detectType(value) that takes a single input and returns a string representing its JavaScript data type. This should return one of the following values accurately:

  • 'string', 'number', 'boolean', 'undefined', 'object', 'function', 'symbol', 'bigint', 'array', or 'null'.
    Note: Since typeof returns 'object' for both arrays and null, you'll need to handle those two as special cases.

Example Inputs & Outputs

detectType("hello") → "string" detectType(123) → "number" detectType(true) → "boolean" detectType(undefined) → "undefined" detectType({}) → "object" detectType([]) → "array" detectType(null) → "null" detectType(function() {}) → "function" detectType(Symbol("id")) → "symbol"

Constraints & Edge Cases

  • Must handle all JavaScript primitive types.
  • Must distinguish between null and object.
  • Must distinguish between array and object.

Solve Similar questions 🔥