Skip to content

Instantly share code, notes, and snippets.

@westc
Last active April 7, 2021 23:31
Show Gist options
  • Save westc/ce3ec0c450389897be6d02e8d3e49d6e to your computer and use it in GitHub Desktop.
Save westc/ce3ec0c450389897be6d02e8d3e49d6e to your computer and use it in GitHub Desktop.
An extended version of the typeOf() function which will either return the name of the class, "null", "undefined" or a boolean indicating if one of the passed type names matches the type of the value.
function typeOf(value) {
for (
var test,
argv = arguments,
argc = argv.length,
i = argc,
typeName = value == undefined
? value === undefined
? 'undefined'
: 'null'
: {}.toString.call(value).slice(8, -1);
--i > 0 && ((typeof(test = argv[i]) == 'string' || typeOf(test) != 'RegExp') ? typeName != test : !test.test(typeName));
);
return argc > 1 ? !!i : typeName;
}
@westc
Copy link
Author

westc commented Sep 2, 2016

Console tests where only the value is supplied:

console.log(typeOf());           // "undefined"
console.log(typeOf(3));          // "Number"
console.log(typeOf([6]));        // "Array"
console.log(typeOf(null));       // "null"
console.log(typeOf(false));      // "Boolean"
console.log(typeOf(typeOf));     // "Function"
console.log(typeOf("Cool!"));    // "String"
console.log(typeOf(new Date));   // "Date"
console.log(typeOf(undefined));  // "undefined"
console.log(typeOf(/^ +| +$/i)); // "RegExp"

Console tests where the value is tested against strings and regular expressions:

console.log(typeOf(3, "Number"));                         // true
console.log(typeOf(4, "String"));                         // false
console.log(typeOf(5, "String", "Number"));               // true
console.log(typeOf("6", /Number|String/));                // true
console.log(typeOf(null, /^[nu]/));                       // true
console.log(typeOf(undefined, /^[A-Z]/, 'undefined'));    // true
console.log(typeOf([6], "Array"));                        // true
console.log(typeOf(false, "Function", "Date"));           // false
console.log(typeOf(true, "Function", "Date", "Boolean")); // true

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment