DEV Community

jser
jser

Posted on • Edited on

BFE.dev #20. Detect data type in JavaScript

BFE.dev is like a LeetCode for Front End developers. I’m using it to practice my skills.

Alt Text

This article is about the coding problem BFE.dev#20. Detect data type in JavaScript

Easy one

This is well-known trick in JavaScript - using Object.prototype.toString() to get the data type.

Nothing fancy, code is here

function detectType(data) {

  let type = ''

  const tag = Object.prototype.toString.call(data)  // '[object Undefined]'
  const matches = tag.match(/\[object (\S+)\]/)

  if (matches) {
    type = matches[1].toLowerCase()
  }

  const allowedTypes = new Set([
    'number',
    'null',
    'string',
    'undefined',
    'bigint',
    'symbol',
    'boolean',
    'array',
    'arraybuffer',
    'date',
    'function',
    'map',
    'set'
    ])

  if (allowedTypes.has(type)) {
    return type
  }

  return 'object'
}
Enter fullscreen mode Exit fullscreen mode

Passed

This is a fairly simple problem.

Alt Text

Hope it helps, you can have a try at here

Top comments (0)