Skip to content

Instantly share code, notes, and snippets.

@amitasaurus
Last active September 17, 2018 10:59
Show Gist options
  • Save amitasaurus/69b83ff25943eaf49e7d094c27d192e2 to your computer and use it in GitHub Desktop.
Save amitasaurus/69b83ff25943eaf49e7d094c27d192e2 to your computer and use it in GitHub Desktop.
Proper Datatypes checking in Javascript
// String
function isString (value) {
return typeof value === 'string' || value instanceof String;
}
// Number
function isNumber (value) {
return typeof value === 'number' && isFinite(value);
}
// Array
function isArray (value) {
return value && typeof value === 'object' && value.constructor === Array;
}
// ES5 actually has a method for this (ie9+)
Array.isArray(value);
//Function
function isFunction (value) {
return typeof value === 'function';
}
// Object
function isObject (value) {
return value && typeof value === 'object' && value.constructor === Object;
}
// Null
function isNull (value) {
return value === null;
}
// Undefined
function isUndefined (value) {
return typeof value === 'undefined';
}
// Boolean
function isBoolean (value) {
return typeof value === 'boolean';
}
// RegExp
function isRegExp (value) {
return value && typeof value === 'object' && value.constructor === RegExp;
}
//Error
function isError (value) {
return value instanceof Error && typeof value.message !== 'undefined';
}
//Date
function isDate (value) {
return value instanceof Date;
}
//Symbol
function isSymbol (value) {
return typeof value === 'symbol';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment