DEV Community

Taufik Nurrohman
Taufik Nurrohman

Posted on • Updated on

Type Checking in JavaScript

I like to group all type checking tasks into helper functions like this to be used internally. This has the advantage in case of code minification 1

function isArray(x) {
    return Array.isArray(x);
}

function isBoolean(x) {
    return false === x || true === x;
}

function isElement(x) {
    return x instanceof Element;
}

function isFloat(x) {
    return isNumber(x) && 0 !== x % 1;
}

function isFunction(x) {
    return 'function' === typeof x;
}

function isInteger(x) {
    return isNumber(x) && 0 === x % 1;
}

function isNull(x) {
    return null === x;
}

function isNumber(x) {
    return 'number' === typeof x;
}

function isNumeric(x) {
    return /^-?(?:\d*\.)?\d+$/.test(x + "");
}

function isObject(x, isPlainObject) {
    if ('object' !== typeof x) {
        return false;
    }
    return isPlainObject ? x instanceof Object : true;
}

function isPattern(x) {
    return x instanceof RegExp;
}

function isSet(x) {
    return 'undefined' !== typeof x && null !== x;
}

function isString(x) {
    return 'string' === typeof x;
}
Enter fullscreen mode Exit fullscreen mode

These functions are very inspired by PHP which already has standard functions such as is_array(), is_object(), is_string(), etc.

There was a proposal to allow users to write the type checking as if ($int instanceof int) {} expression somewhere. I don’t know where the page is. I couldn’t find it anymore.

Update: found it!

Update: Is now available as Node.js module.

GitHub logo taufik-nurrohman / is

Conditional utility.

Conditional Utility

I like to group all type checking tasks into helper functions like this to be used internally. This has the advantage in case of code minification.

These functions are very inspired by PHP which already has standard functions such as is_array(), is_object(), is_string(), etc.

Usage

CommonJS

const {isString} = require('@taufik-nurrohman/is');

console.log(isString('false'));
Enter fullscreen mode Exit fullscreen mode

ECMAScript

import {isString} from '@taufik-nurrohman/is';

console.log(isString('false'));
Enter fullscreen mode Exit fullscreen mode

Methods

isArray(any)

isBoolean(any)

isDefined(any)

isFloat(number)

isFunction(any)

isInstance(object, constructor)

isInteger(number)

isNull(any)

isNumber(any)

isNumeric(string)

isObject(any, isPlain = true)

isScalar(any)

isSet(any)

isString(any)


  1. Unless you specify it as object property in the library like jQuery.isString = function(x) {};. You cannot minify object property in any way. 

Latest comments (0)