Skip to content
JavaScript

Type Checking

Precisely determine JavaScript data types.

By EZ4Code Team
typecheck

Code

function getType(val) {
  return Object.prototype.toString.call(val).slice(8, -1).toLowerCase();
}

const is = {
  array: v => Array.isArray(v),
  object: v => getType(v) === "object",
  function: v => typeof v === "function",
  string: v => typeof v === "string",
  number: v => typeof v === "number" && !isNaN(v),
  promise: v => getType(v) === "promise"
};

Explanation

Uses Object.prototype.toString to precisely determine various data types.

More JavaScript Snippets