← Download MyJS
MyJS block
typeOf 1.0.0
Gets the type of any value.
- Exports
-
typeOf - Works in
- Browser and Node.js
The code of version 1.0.0
/**
* Gets the type of a value, as a name like `"Array"`, `"RegExp"` or
* `"Promise"`. It goes further than `typeof`, which calls arrays, dates,
* regular expressions and `null` all `"object"`.
*
* The name comes from, in order:
*
* - `"Null"` for `null` and `"Undefined"` for `undefined`.
* - The name of the value's constructor. Instances of your own classes get
* the class's name (`"Person"`), and values from other frames or windows
* work too.
* - The tag that `Object.prototype.toString()` gives (e.g. `"Object"` for
* objects made with `Object.create(null)`, which have no constructor).
* - Its `typeof`, capitalized, if both of those throw (e.g. for a revoked
* `Proxy`).
*
* The constructor's name is trusted, so an object whose `constructor`
* property is set to something else (`{constructor: Array}`) gets that name.
*
* @param {*} value
* The value whose type is wanted.
* @returns {string}
* The type's name, starting with a capital letter.
*
* @example
* typeOf([3, 6, 2]); // "Array"
* typeOf(/^[aeiou]/i); // "RegExp"
* typeOf(new Date()); // "Date"
* typeOf(null); // "Null"
* typeOf(undefined); // "Undefined"
* typeOf(42); // "Number"
* typeOf('hi'); // "String"
* typeOf(10n); // "BigInt"
* typeOf(async () => {}); // "AsyncFunction"
*
* @example
* // Instances of classes get the class's name
* class Person {}
* typeOf(new Person()); // "Person"
*
* // Objects without a constructor fall back to their tag
* typeOf(Object.create(null)); // "Object"
*/
function typeOf(value) {
if (value === null) return 'Null';
if (value === undefined) return 'Undefined';
try {
const name = value.constructor?.name;
if (typeof name === 'string' && name) return name;
} catch { /* constructor lookup failed; fall back to toString */ }
try {
return Object.prototype.toString.call(value).slice(8, -1);
}
catch {
const t = typeof value;
return t[0].toUpperCase() + t.slice(1);
}
}
Versions
-
1.0.0 Oct 16, 2026
Initial