Javascript get type of class

typeof

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

Try it

Syntax

Parameters

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.

Type Result
Undefined «undefined»
Null «object» (reason)
Boolean «boolean»
Number «number»
BigInt «bigint»
String «string»
Symbol «symbol»
Function (implements [[Call]] in ECMA-262 terms; classes are functions as well) «function»
Any other object «object»

This list of values is exhaustive. No spec-compliant engines are reported to produce (or had historically produced) values other than those listed.

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

Browser compatibility

BCD tables only load in the browser

See also

Источник

JavaScript – Get the Name of an Object’s Type

While working with JavaScript, the developers might need to retrieve the name of an object’s type. As we know, the Object class indicates one of JavaScript’s data types. This technique is utilized for multiple reasons, such as debugging code to identify errors, useful for implementing polymorphism, and so on.

This tutorial will demonstrate the methods for getting the name of the object’s type in JavaScript.

How to Get/Retrieve the Name of an Object’s Type in JavaScript?

To get the name of the object type, use the following mentioned approaches:

Method 1: Get the Name of an Object’s Type Using “typeof” Operator

Use the “typeof” operator, to retrieve the name of an object’s type. It gives a string that indicates the type of the operand or variable.

Utilize the following syntax for getting the name of an Object’s type using the “typeof” operator:

Here, in the given example, we will first create a variable “a” and assign it a number “15”:

Then, check the type of the variable utilizing the “typeof” operator:

It can be shown that the output displays “number” that indicates the data type of the variable “a”:

Now, we will store a string in variable “a” and check the type:

The specified operator returns the type of “a” as “string”:

It should be noted that the “typeof” operator may not always return the exact name of the object’s type. For instance, it will output “object” for arrays.

Let’s see an example to see this concept.

Create an array and store it in a variable “a”:

Check the type of variable “a” using the “typeof” operator:

As you can see that the output displays “object” not specify its type:

So, in that case, use the “constructor ” property for retrieving the type of an object.

Method 2: Get the Name of an Object’s Type Using “constructor ” Property

Utilize the “constructor” property with the “name” attribute to get the name of the object’s type. It gives the name of the constructor function that created the object.

The given syntax is utilized for using the “constructor” property to get the name of the object type:

Use the “constructor” property to get the name of the object type:

As you can see, the specified property outputs “Array”, which is the actual type of the object “a”:

Method 3: Get the Name of an Object’s Type Using “Object.prototype.toString.call()” Method

You can also use the “Object.prototype.toString.call()” method for determining the data type of a given variable or operand. The “Object.prototype.toString.call()” method is more efficient than the typeof operator.

Follow the given syntax for getting the name of an object type:

Assign a string to the variable “a” and check the type of the object:

Here, we will check the type of “a” that stores an array:

It gives the accurate result of the name of the object type:

That was all about getting the name of the object type in JavaScript.

Conclusion

For getting or retrieving the name of the object type, use the “typeof” operator, “constructor” property with the “name” attribute, or the “Object.prototype.toString.call()” method. This tutorial demonstrated the methods for getting the name of the object’s type in JavaScript.

About the author

Farah Batool

I completed my master’s degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.

Источник

Читайте также:  Отличие get от post php
Оцените статью