Javascript check custom object type

How can I check if my javascript object is of a certain type.

var SomeObject = function() { }
var s1 = new SomeObject();

In the case above typeof s1 will return "object". That's not very helpful. Is there some way to check if s1 is of type SomeObject ?

asked Sep 28, 2009 at 10:12

Yes, using instanceof (MDN link | spec link):

if (s1 instanceof SomeObject) { ... }

answered Sep 28, 2009 at 10:14

Javascript check custom object type

T.J. CrowderT.J. Crowder

983k181 gold badges1829 silver badges1803 bronze badges

3

Whatever you do, avoid obj.constructor.name or any string version of the constructor. That works great until you uglify/minify your code, then it all breaks since the constructor gets renamed to something obscure (ex: 'n') and your code will still do this and never match:

// Note: when uglified, the constructor may be renamed to 'n' (or whatever),
// which breaks this code since the strings are left alone.
if (obj.constructor.name === 'SomeObject') {}

Note:

// Even if uglified/minified, this will work since SomeObject will
// universally be changed to something like 'n'.
if (obj instanceof SomeObject) {}

(BTW, I need higher reputation to comment on the other worthy answers here)

answered Jul 24, 2016 at 1:39

AAronAAron

3942 silver badges11 bronze badges

1

Idea stolen from http://phpjs.org/functions/get_class/, posted by SeanJA. Ripped down to work with objects only and without need for a regular expression:

function GetInstanceType(obj)
{
    var str = obj.constructor.toString();
    return str.substring(9, str.indexOf("("));
}

function Foo() {
    this.abc = 123;
}

// will print "Foo"
GetInstanceType(new Foo());

I just learned an easier way to extract the function name from the constructor:

obj.constructor.name

answered Apr 1, 2015 at 16:19

Javascript check custom object type

kungfoomankungfooman

4,1161 gold badge40 silver badges30 bronze badges

2

While instanceof is a correct answer it sure is ugly syntax. I offer that if you are creating custom objects you can add your own property for type and check against that like so...

var Car = function(){
    this.type = Object.defineProperty(this, "type", {value:"Car"});
}

This would create an immutable property called type that lives with the object. If you were using the Class syntax you could make it static as well.

... somewhere later ...

function addCar(car){
    if (car.type != "Car"){
        throw Error("invalid type for car");
    }

...

I think this solution is easy to implement, more intuitive, and thus easier for others to use and maintain.

answered Apr 4, 2019 at 17:40

Javascript check custom object type

The typeof operator returns a string indicating the type of the operand's value.

Try it

Syntax

Parameters

operand

An expression representing the object or primitive whose type is to be returned.

Description

The following table summarizes the possible return values of typeof. For more information about types and primitives, see also the JavaScript data structure page.

This list of values is exhaustive. No spec-compliant engines are reported to produce (or had historically produced) values other than those listed. The old Internet Explorer was the only browser known to implement additional return values, before the spec removed the behavior of typeof returning implementation-defined strings for non-callable non-standard exotic objects.

Examples

Basic usage

// Numbers
typeof 37 === "number";
typeof 3.14 === "number";
typeof 42 === "number";
typeof Math.LN2 === "number";
typeof Infinity === "number";
typeof NaN === "number"; // Despite being "Not-A-Number"
typeof Number("1") === "number"; // Number tries to parse things into numbers
typeof Number("shoe") === "number"; // including values that cannot be type coerced to a number

typeof 42n === "bigint";

// Strings
typeof "" === "string";
typeof "bla" === "string";
typeof `template literal` === "string";
typeof "1" === "string"; // note that a number within a string is still typeof string
typeof typeof 1 === "string"; // typeof always returns a string
typeof String(1) === "string"; // String converts anything into a string, safer than toString

// Booleans
typeof true === "boolean";
typeof false === "boolean";
typeof Boolean(1) === "boolean"; // Boolean() will convert values based on if they're truthy or falsy
typeof !!1 === "boolean"; // two calls of the ! (logical NOT) operator are equivalent to Boolean()

// Symbols
typeof Symbol() === "symbol";
typeof Symbol("foo") === "symbol";
typeof Symbol.iterator === "symbol";

// Undefined
typeof undefined === "undefined";
typeof declaredButUndefinedVariable === "undefined";
typeof undeclaredVariable === "undefined";

// Objects
typeof { a: 1 } === "object";

// use Array.isArray or Object.prototype.toString.call
// to differentiate regular objects from arrays
typeof [1, 2, 4] === "object";

typeof new Date() === "object";
typeof /regex/ === "object";

// The following are confusing, dangerous, and wasteful. Avoid them.
typeof new Boolean(true) === "object";
typeof new Number(1) === "object";
typeof new String("abc") === "object";

// Functions
typeof function () {} === "function";
typeof class C {} === "function";
typeof Math.sin === "function";

typeof null

// This stands since the beginning of JavaScript
typeof null === "object";

In the first implementation of JavaScript, JavaScript values were represented as a type tag and a value. The type tag for objects was 0. null was represented as the NULL pointer (0x00 in most platforms). Consequently, null had 0 as type tag, hence the typeof return value "object". (reference)

A fix was proposed for ECMAScript (via an opt-in), but was rejected. It would have resulted in typeof null === "null".

Using new operator

All constructor functions called with new will return non-primitives ("object" or "function"). Most return objects, with the notable exception being Function, which returns a function.

const str = new String("String");
const num = new Number(100);

typeof str; // "object"
typeof num; // "object"

const func = new Function();

typeof func; // "function"

Need for parentheses in syntax

The typeof operator has higher precedence than binary operators like addition (+). Therefore, parentheses are needed to evaluate the type of an addition result.

// Parentheses can be used for determining the data type of expressions.
const someData = 99;

typeof someData + " Wisen"; // "number Wisen"
typeof (someData + " Wisen"); // "string"

Interaction with undeclared and uninitialized variables

typeof is generally always guaranteed to return a string for any operand it is supplied with. Even with undeclared identifiers, typeof will return "undefined" instead of throwing an error.

typeof undeclaredVariable; // "undefined"

However, using typeof on lexical declarations (let const, and class) in the same block before the line of declaration will throw a ReferenceError. Block scoped variables are in a temporal dead zone from the start of the block until the initialization is processed, during which it will throw an error if accessed.

typeof newLetVariable; // ReferenceError
typeof newConstVariable; // ReferenceError
typeof newClass; // ReferenceError

let newLetVariable;
const newConstVariable = "hello";
class newClass {}

Exceptional behavior of document.all

All current browsers expose a non-standard host object document.all with type undefined.

typeof document.all === "undefined";

Although document.all is also falsy and loosely equal to undefined, it is not undefined. The case of document.all having type "undefined" is classified in the web standards as a "willful violation" of the original ECMAScript standard for web compatibility.

Custom method that gets a more specific type

typeof is very useful, but it's not as versatile as might be required. For example, typeof [] is "object", as well as typeof new Date(), typeof /abc/, etc.

For greater specificity in checking types, here we present a custom type(value) function, which mostly mimics the behavior of typeof, but for non-primitives (i.e. objects and functions), it returns a more granular type name where possible.

function type(value) {
  if (value === null) {
    return "null";
  }
  const baseType = typeof value;
  // Primitive types
  if (!["object", "function"].includes(baseType)) {
    return baseType;
  }

  // Symbol.toStringTag often specifies the "display name" of the
  // object's class. It's used in Object.prototype.toString().
  const tag = value[Symbol.toStringTag];
  if (typeof tag === "string") {
    return tag;
  }

  // If it's a function whose source code starts with the "class" keyword
  if (
    baseType === "function" &&
    Function.prototype.toString.call(value).startsWith("class")
  ) {
    return "class";
  }

  // The name of the constructor; for example `Array`, `GeneratorFunction`,
  // `Number`, `String`, `Boolean` or `MyCustomClass`
  const className = value.constructor.name;
  if (typeof className === "string" && className !== "") {
    return className;
  }

  // At this point there's no robust way to get the type of value,
  // so we use the base implementation.
  return baseType;
}

For checking potentially non-existent variables that would otherwise throw a ReferenceError, use typeof nonExistentVar === "undefined" because this behavior cannot be mimicked with custom code.

Specifications

Specification
ECMAScript Language Specification
# sec-typeof-operator

Browser compatibility

BCD tables only load in the browser

See also

How do I know the type of an object?

Use the typeof operator to get the type of an object or variable in JavaScript. The typeof operator also returns the object type created with the "new" keyword. As you can see in the above example, the typeof operator returns different types for a literal string and a string object.

How do I know my TS type?

Use the typeof operator to check the type of a variable in TypeScript, e.g. if (typeof myVar === 'string') {} . The typeof operator returns a string that indicates the type of the value and can be used as a type guard in TypeScript.

How do you check what type a variable is in JavaScript?

typeof is a JavaScript keyword that will return the type of a variable when you call it. You can use this to validate function parameters or check if variables are defined. There are other uses as well. The typeof operator is useful because it is an easy way to check the type of a variable in your code.

How do you check if it is an object in JavaScript?

Method 1: Using the typeof operator The typeof operator returns the type of the variable on which it is called as a string. The return string for any object that does not exist is “undefined”. This can be used to check if an object exists or not, as a non-existing object will always return “undefined”.