Check if value is of type

OSCC · JavaScript, Type, Array · Oct 20, 2020

Checks if the provided value is of the specified type.

const is = (type, val) => ![, null].includes(val) && val.constructor === type;
is(Array, [1]); // true
is(ArrayBuffer, new ArrayBuffer()); // true
is(Map, new Map()); // true
is(RegExp, /./g); // true
is(Set, new Set()); // true
is(WeakMap, new WeakMap()); // true
is(WeakSet, new WeakSet()); // true
is(String, ''); // true
is(String, new String('')); // true
is(Number, 1); // true
is(Number, new Number(1)); // true
is(Boolean, true); // true
is(Boolean, new Boolean(true)); // true

Recommended snippets

  • Value is array-like

    JavaScript, Type

    Checks if the provided argument is array-like (i.e. is iterable).

  • Collection is empty

    JavaScript, Type

    Checks if the a value is an empty object/collection, has no enumerable properties or is any type that is not considered a collection.

  • Value is plain object

    JavaScript, Type

    Checks if the provided value is an object created by the Object constructor.