23.07.2020

Javascript check the type of a variable. JavaScript, typeof, types and classes. Get operator typeof


  • Undefined: "undefined"
  • Null: "object"
  • Boolean: "boolean"
  • Number: "number"
  • String: "string"
  • Function: "function"
  • Everything else: "object"

The following notes should be added to this table:

1. typeof null === "object".

Theoretically, this is a subtle point. In statically typed languages, an object type variable may not contain an object (NULL, nil, null pointer).

In practice, this is inconvenient in JavaScript. So the ES 5.1 developers are going to do a more intuitive thing: typeof null === "null".

But since we have ES3 so far, make no mistake, for example, on this:

/ * The function searches for some object and returns it or null if nothing is found * / function search () () var obj = search (); if (typeof obj === "object") (// did we actually find the object (FAIL) obj.method ();)

2. Don't forget about wrapper objects (typeof new Number (5) === "object").

3. And do not forget about the right of browsers to do anything with host-objects.

Don't be surprised that Safari stubbornly thinks HTMLCollection is a function type, and IE before version 9 kept our favorite alert () function as an object. Also Chrome used to think of RegExp as function, but now it seems to have sensed and respond to it with object.

toString ()

Trying to find out the type of a value from the result of its toString () method is pointless. In all "classes" this method is redefined to its own.

The method is good for displaying debug information, but the type of a variable cannot be determined by it.

Object.prototype.toString ()

Although toString is redefined within concrete "classes", we still have its original implementation from Object. Let's try to use it:

console.log (Object .prototype .toString .call (value));

console.log (Object.prototype.toString.call (value));


Clinton dilutes this burden

Ironically, this method works surprisingly well.

For scalar types, returns,,,.

The funny thing is that even new Number (5) on which typeof failed here returns.

The method fails on null and undefined. Different browsers return, sometimes expected, and sometimes in general. However, it is easy to determine the type of these two values ​​without it.

The fun begins when we get to objects (those with typeof === "object").

built-in objects work out, practically, with a bang:

  • {} —
  • Date -
  • Error -
  • RegExp -

The only thing that falls out of the list of arguments is that, then.
With host objects, things are getting worse again.

In IE, DOM objects began to become "normal" objects only from the 8th version, and then not quite to the end. Therefore, in IE 6-8, all these objects (HTMLCOllection, DOMElement, TextNode, and along with document and window) are converted to simply.

In all other browsers (including IE9), you can already do something with the result of toString. Although everything is also not easy: HTMLCollection is there, then. window - then, then, then. But you can already try to get something out of this.

It is more difficult with DOMElement: it is displayed as, - its own format for each tag. But here, the regular season will help us.

The story is about the same with other host objects (in the location and navigator tests). Everywhere, except IE, they can be identified by string.

Of the cons of using Object.prototype.toString ():

1. This opportunity is not sanctified by the standard. And here we should rather rejoice that everything is working so well, and not lament over some flaws.

2. Determining the type by parsing the string returned by a method that is not at all for determining the type, and is also called on an object to which it does not belong, leaves some residue on the soul.

3. In old IE, as you can see, host objects are normally not identified.

However, it is quite a working piece when used in conjunction with other tools.


Constructors

And finally, constructors. Who better to say about the "class" of an object in JS if not its constructor?

Null and undefined have neither wrapper objects nor constructors.

The rest of the scalar types have wrappers, respectively, you can get a constructor:

(5) .constructor === Number; (Number .NaN) .constructor === Number; (true) .constructor === Boolean; ("string") .constructor === String;

(5) .constructor === Number; (Number.NaN) .constructor === Number; (true) .constructor === Boolean; ("string"). constructor === String;

But instanceof will not work here:

5 instanceof Number; // false Number .NaN instanceof Number; // false true instanceof Boolean; // false "string" instanceof String; // false

5 instanceof Number; // false Number.NaN instanceof Number; // false true instanceof Boolean; // false "string" instanceof String; // false

(instanceof will work for the long-suffering new Number (5))

With functions (which are also objects), instanceof will pass:

console.log ((function () ()) instanceof Function); // true console.log ((function () ()) .constructor === Function); // true

console.log ((function () ()) instanceof Function); // true console.log ((function () ()). constructor === Function); // true

All objects of built-in classes are also easily identified by their constructors: Array, Date, RegExp, Error.

One problem arises here with arguments, whose constructor is Object.

And the second with the Object itself, or rather, how to refer to it an object created through a custom constructor.

Only the base object can be defined this way:

obj instanceof Object;

As one of the variants of the definition - to iterate over all other possible types (Array, Error ...) and if none matches - "object".

Constructors and host objects

With host objects, things are getting worse.

Let's start with the fact that IE up to and including version 7 does not consider them as normal objects at all. They simply do not have constructors and prototypes there (in any case, the programmer cannot reach them).

Other browsers do better. There are constructors and you can use them to determine the value class. Only they are called differently in different browsers. For example, for HTMLCollection, the constructor will be either HTMLCollection or NodeList, or even NodeListConstructor.

You should also define a base constructor for DOMElement. In FF, this is, for example, HTMLElement, from which HTMLDivElement and others are already inherited.

FireFox below version 10 and Opera below version 11 throw up a prank. There the collection constructor is Object.

constructor.name

Constructors also have a name property that can be useful.

It contains the name of the constructor function, for example (5) .constructor.name === "Number".

But:
1. In IE it is not at all, even in the 9th.
2. Browsers again sculpt everything into Host-objects (and often they do not have this property at all). In Opera, DOMElement has a constructor name in general Function.prototype.
3. arguments is again "object".

conclusions

None of the presented methods provide one hundred percent definition of the type / class of the value in all browsers. However, together they allow you to do this.

In the near future I will try to collect all the data in tables and give an example of a defining function.

Dynamic type identification

Dynamic Type Identification (RTTI) allows you to determine the type of an object at runtime. It turns out to be useful for a variety of reasons. In particular, by reference to the base class, you can fairly accurately determine the type of object available from this link. Dynamic type identification also allows you to check in advance how successful the typecast will be, preventing an invalid typecast exception. In addition, dynamic type identification is a major component of reflection.

To support dynamic type identification, C # provides three keywords a: is, as and typeof. Each of these keywords is discussed below in turn.

Is operator

The specific type of an object can be determined using the is operator. Its general form is shown below:

expression is type

where expression denotes a separate expression describing the object whose type is being checked. If the expression is of a compatible type or of the same type as the type being tested, then the result of this operation is true, otherwise it is false. Thus, the result is true if the expression has a testable type in one form or another. The is operator defines both types to be compatible if they are of the same type, or if reference conversion, boxing, or unboxing is provided.

Below is an example of using the is operator:

Using System; namespace ConsoleApplication1 (class Add () class Sum: Add () class Program (static void Main () (Add a = new Add (); Sum s = new Sum (); if (a is Add) Console.WriteLine ("Variable a is of type Add "); if (s is Sum) Console.WriteLine (" The type of s is inherited from the Add class "); Console.ReadLine ();)))

As operator

Sometimes the type conversion needs to be done at runtime, but not throw an exception if the conversion fails, which is quite possible with type casting. For this purpose, the as operator serves, which has the following general form:

expression as type

where expression denotes a single expression to be converted to the specified type.

If this conversion succeeds, then a reference to the type is returned; otherwise, an empty reference. The as operator can only be used for reference conversion, identity, boxing, unboxing. In some cases, the as operator can serve as a convenient alternative to the is operator. As an example, consider the following program:

Using System; namespace ConsoleApplication1 (class Add () class Sum: Add () class Program (static void Main () (Add a = new Add (); Sum s = new Sum (); // Perform typecasting a = s as Add; if (a! = null) Console.WriteLine ("Conversion was successful"); else Console.WriteLine ("Conversion failed"); Console.ReadLine ();)))

The result of this program will be a successful conversion.

Operator typeof returns a string indicating the type of the operand.

Syntax

The operand follows the typeof operator:

Typeof operand

Options

operand is an expression representing an object, or primitive, the type of which should be returned.

Description

The following table lists the possible return values ​​of typeof. More information about types and primitives is on the page.

Examples of

// Numbers typeof 37 === "number"; typeof 3.14 === "number"; typeof (42) === "number"; typeof Math.LN2 === "number"; typeof Infinity === "number"; typeof NaN === "number"; // even though it is "Not-A-Number" typeof Number (1) === "number"; // never use this entry! // Strings typeof "" === "string"; typeof "bla" === "string"; typeof "1" === "string"; // note that the number inside the string is still of type string typeof (typeof 1) === "string"; // typeof will always return a string in this case typeof String ("abc") === "string"; // never use this entry! // Booleans typeof true === "boolean"; typeof false === "boolean"; typeof Boolean (true) === "boolean"; // never use this entry! // 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 distinguish between regular objects and arrays typeof === "object"; typeof new Date () === "object"; // What is below leads to errors and problems. Do not use! 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";

null

// This has been defined since birth JavaScript typeof null === "object";

In the first implementation JavaScript values were represented by a pair of tag type and value. The tag type for objects was 0. null was represented as a null pointer (0x00 on most platforms). Hence the tag type for null was zero, so the return value of typeof is bogus. ()

A fix was suggested in ECMAScript (via disable) but was rejected. This would result in typeof null === "null".

Using the new operator

// All constructor functions created with "new" will be of type "object" var str = new String ("String"); var num = new Number (100); typeof str; // Returns "object" typeof num; // Returns "object" // But there is an exception for the Function constructor var func = new Function (); typeof func; // Returns "function"

Regular Expressions

Called regular expressions were a non-standard add-on in some browsers.

Typeof / s / === "function"; // Chrome 1-12 Not ECMAScript 5.1 compliant typeof / s / === "object"; // Firefox 5+ ECMAScript 5.1 Compliant

Errors related to temporary dead zones

Prior to ECMAScript 2015, the typeof operator was guaranteed to return a string for whatever operand it was called with. This changed after adding non-rolling ads let and const block-scoped. Now, if variables are declared with let and const, and typeof is called for them in the variable declaration block, but before the declaration, then it is thrown ReferenceError... The behavior differs from undeclared variables, for which typeof will return "undefined". Block-scoped variables are in " time dead zone", which lasts from the beginning of the block until the moment the variables are declared. In this zone, an attempt to access the variables throws an exception.

Typeof undeclaredVariable === "undefined"; typeof newLetVariable; let newLetVariable; // ReferenceError typeof newConstVariable; const newConstVariable = "hello"; // ReferenceError

Exceptions

In all current browsers there is a non-standard host object document.all which is of type Undefined.

Typeof document.all === "undefined";

Although the specification allows custom type names for non-standard exotic objects, it is required that these names differ from the predefined ones. A situation where document.all is undefined should be considered an exceptional violation of the rules.

Specifications (edit)

Specification Status Comments (1)
ECMAScript Latest Draft (ECMA-262)
Draft
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of "The typeof Operator" in this specification.
Standard
ECMAScript 5.1 (ECMA-262)
The definition of "The typeof Operator" in this specification.
Standard
ECMAScript 3rd Edition (ECMA-262)
The definition of "The typeof Operator" in this specification.
Standard
ECMAScript 1st Edition (ECMA-262)
The definition of "The typeof Operator" in this specification.
Standard Original definition. Implemented in JavaScript 1.1

Browser Compatibility

Update compatibility data on GitHub

ComputersMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
typeofChrome Full support 1 Edge Full support 12 Firefox Full support 1 IE Full support 3 Opera Full support YesSafari Full support YesWebView Android Full support 1 Chrome Android Full support 18 Firefox Android Full support 4 Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support 1.0 nodejs Full support Yes

Legend

Full support Full support

IE specific notes

In IE 6, 7, and 8, many host objects are objects, but not functions. For example.


2021
maccase.ru - Android. Brands. Iron. news