Contacts

JavaScript Check the type of variable. How to verify the type of variable in JavaScript. TypeOf receipt operator

Javascript. or JS. (Abbreviated) Not a simple language and novice developers will not know about it immediately. At first they recognize the basics and everything seems colorful and beautiful. Looking for a little deeper, JavaScript appears arrays, objects, callbacks and everything like that often makes the brain.

JavaScript is important to correctly check the type of variable. Suppose you want to know whether a variable with an array or object? How to check it right? In this particular case, there are tricks during the inspection and this will be this entry. Let's immediately proceed.

Variable type check

For example, you need to check is an object variable, an array, string or number. To do this, you can use Typeof, but it will not always give the truth and in the example below I will show why.

I wrote this example to vividly show why Typeof is not always the right choice.

Var _comparison \u003d (string: "String", int: 99, float: 13.555, object: (Hello: "Hi"), Array: New Array (1, 2, 3)); // Return an array with the keys of the VAR _Objkeys object \u003d object.keys (_Comparison); for (var i \u003d 0; i<= _objKeys.length - 1; i++) { // выведем в консоль тип каждой переменной console.log(typeof _comparson[_objKeys[i]]); }

Code execution result:

STRING NUMBER NUMBER OBJECT OBJECT

Right? - Of course not. There are two problems. Each of them will be described in detail and suggested.

First problem: Float number, output as Number

COMPARISON.FLOAT is not a number and instead of Number must be Float (a floating point number). This is fixed, you can create a check function as in the code below.

Var _floatnumber \u003d 9.22; var _notfloatnumber \u003d 9; Console.log (ISFLoat (_FloatNumber)); Console.log (ISFLOAT (_NotFloatNumber)); Console.log (ISFLoat (")); Function IsFloat (N) (Return Number (N) \u003d\u003d\u003d N && N% 1! \u003d\u003d 0;)

The iSfloat () function performs checking all values \u200b\u200bto the floating point numbers. Is first checked whether the variable is equal n. number (number (n) \u003d\u003d\u003d n) and if yes, then another validation check is made with the residue and if there is a residue, then the buleva returns ( true. or false) Result (N% 1! \u003d\u003d 0).

In the example above it returns true., false and false. The first value is float.type, the second is not - this is the usual number and the last just an empty string that does not suit the rules.

Second problem: the array was determined as an object

In the very first example, the array was displayed as an object and it is not very good, since sometimes you need to use this particular type and nothing more.

There are several ways to check the variable on the type of array.

First option (good option). Check the DATA accessory to the array using instanceof ().

Var data \u003d new array ("hello", "world"); Var Isarr \u003d Data InstanceOf Array;

Second version (good option). The array.isarray () method returns the boolean value, which will depend on whether the variable is an array or not ().

Var data \u003d new array ("hello", "world"); var isarr \u003d array.isarray (DATA);

Third option (the best, but long). For convenience, you can make this way function. Using Object, we do. If the result Object.Prototype.tostring.call (DATA) is not equal to the variable is not an array ().

Var data \u003d new array ("hello", "world"); var isarr \u003d object.prototype.tostring.call (DATA) \u003d\u003d ""; Console.log (ISARR);

The last result in the form of a convenient function:

Function Isarray (Data) (Return Object.Prototype.tostring.call (DATA) \u003d\u003d "")

Now you can call the ISARRAY () functions and as an argument to set an array or something else and see the result.

Afterword

The recording turned out quite large than originally thought. But I am satisfied with it, because she briefly and clearly describes difficulties when checking the variables in JavaScript and how to get around them.

If you have any questions left - write them below to this record. I will be happy to help.

Operator Typeof. Returns the string indicating the type of operand.

Syntax

Operand follows the TypeOf operator:

Typeof. operand.

Parameters

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

Description

The following table shows the possible returned TypeOf values. Additional information about types and primitives is on the page.

Examples

// Numbers TypeOf 37 \u003d\u003d\u003d "Number"; Typeof 3.14 \u003d\u003d\u003d "Number"; TypeOF (42) \u003d\u003d\u003d "Number"; Typeof Math.ln2 \u003d\u003d\u003d "Number"; Typeof Infinity \u003d\u003d\u003d "Number"; Typeof nan \u003d\u003d\u003d "Number"; // Despite the fact that it is "not-a-number" (not number) Typeof Number (1) \u003d\u003d\u003d "Number"; // Never use this entry! // String Typeof "" \u003d\u003d\u003d "String"; Typeof "bla" \u003d\u003d\u003d "String"; Typeof "1" \u003d\u003d\u003d "String"; // Please note that the number inside the string still has a typeOf string type (TypeOF 1) \u003d\u003d\u003d "String"; // Typeof will always return in this case the TypeOf String string ("ABC") \u003d\u003d\u003d "String"; // Never use this entry! // Booleans Typeof True \u003d\u003d\u003d "Boolean"; Typeof false \u003d\u003d\u003d "Boolean"; Typeof Boolean (True) \u003d\u003d\u003d "Boolean"; // Never use this entry! // Syms symbols Symbol () \u003d\u003d\u003d "Symbol" Typeof Symbol ("foo") \u003d\u003d\u003d "Symbol" Typeof Symbol.iterator \u003d\u003d\u003d "Symbol" // undefined Typeof undefined \u003d\u003d\u003d "undefined"; Typeof declaredbutundefinedvariable \u003d\u003d\u003d "undefined"; Typeof undeclaredvariable \u003d\u003d\u003d "undefined"; // TypeOF objects (A: 1) \u003d\u003d\u003d "Object"; // Use array.isarray or object.prototype.tostring.call // To distinguish between the usual objects and TypeOf \u003d\u003d\u003d "Object" arrays; Typeof New Date () \u003d\u003d\u003d "Object"; // That lower leads to errors and problems. Do not use! Typeof New Boolean (True) \u003d\u003d\u003d "Object"; Typeof New Number (1) \u003d\u003d\u003d "Object"; Typeof New String ("ABC") \u003d\u003d\u003d "Object"; // functions typeof function () () \u003d\u003d\u003d "FUNCTION"; Typeof Class C () \u003d\u003d\u003d "FUNCTION"; Typeof Math.sin \u003d\u003d\u003d "FUNCTION";

nULL

// It was determined from the birth of JavaScript Typeof NULL \u003d\u003d\u003d "Object";

In the first implementation of JavaScript, the values \u200b\u200bwere presented by a pair Tag type and value. Tag Tag for objects was 0. NULL was represented as a zero pointer (0x00 in most platforms). Consequently, the tag type for NULL was zero, so the return value of Typeof is fictitious. ()

The correction was asked in Ecmascript (through shutdown), but was rejected. This would lead to the fact that Typeof null \u003d\u003d\u003d "NULL".

Using the NEW operator

// All functions-designers created using "New" will have the type "Object" var string \u003d New String ("String"); var num \u003d new number (100); Typeof str; // Return "Object" Typeof Num; // will return "Object" // But there is an exception for the FUNCTION VAR FUNC \u003d New Function () constructor; Typeof Func; // Return "FUNCTION"

Regular expressions

Called regular expressions were non-standard supplement in some browsers.

TypeOf / s / \u003d\u003d\u003d "FUNCTION"; // Chrome 1-12 does not match Ecmascript 5.1 Typeof / S / \u003d\u003d\u003d "Object"; // Firefox 5+ corresponds to ECMAScript 5.1

Errors associated with temporary dead zones

Before Ecmascript 2015, it was guaranteed that the TypeOf operator will return a string for any operand with which it was called. This has changed after adding non-submissive Let and Const ads with block area of \u200b\u200bvisibility. Now, if the variables are declared using Let and Const, and for them is called TypeOF in the class declaration unit, but before the announcement, referencerReError is ejected. Behavior differs from undeclared variables for which Typeof will return "undefined". Variables with a block area of \u200b\u200bvisibility are in the "temporary dead zone" that lasts from the beginning of the block until the declaration of variables. In this zone, an attempt to access variables is thrown out an exception.

Typeof undeclaredvariable \u003d\u003d\u003d "undefined"; Typeof NewletVariable; Let NewletVariable; // ReferenceError Typeof newconstvariable; Const newconstvariable \u003d "Hello"; // ReferenceError

Exceptions

In all current browsers there is a non-standard Document.all host object, which has type undefined.

Typeof Document.all \u003d\u003d\u003d "undefined";

Although the specification permits its own types of types for non-standard exotic objects, it is required that these names differ from predefined. The situation when Document.all has type undefined should be considered as an exceptional violation of the rules.

Specifications

Specification Status Comments
ECMAScript Latest Draft (ECMA-262)
Draft
ECMASCRIPT 2015 (6th Edition, ECMA-262)
Definition "The Typeof Operator" in this specification.
Standard
ECMASCRIPT 5.1 (ECMA-262)
Definition "The Typeof Operator" in this specification.
Standard
ECMAScript 3RD Edition (ECMA-262)
Definition "The Typeof Operator" in this specification.
Standard
ECMAScript 1st Edition (ECMA-262)
Definition "The Typeof Operator" in this specification.
Standard Initial definition. Implemented in JavaScript 1.1

Compatibility with browsers

Update Compatibility Data On GitHub

ComputersMobileServer
Chrome.Edge.Firefox.Internet Explorer.Opera.Safari.Android WebView.Chrome for AndroidFirefox for AndroidOpera for AndroidSafari on ios.Samsung internetNode.js.
Typeof.Chrome. 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 notions

In IE 6, 7 and 8, many HOST objects are objects, but not features. For example.

Dynamic identification of types

Dynamic Type Identification (RTTI) Allows you to determine the type of object during program execution. It turns out to be useful for a number of reasons. In particular, by reference to the base class, it is possible to quite accurately determine the type of object available at this link. The dynamic identification of types also makes it possible to check in advance how successful will the outcome of the type of type bringing, preventing the exclusive situation in connection with the incorrect viewing of the types. In addition, the dynamic identification of types is the main component of reflection.

To support the dynamic identification of types in C #, three keywords are provided: IS, AS and Typeof. Each of these keywords is considered further in turn.

Operator IS.

The specific type of object can be determined using the IS operator. Below is its common form:

iS type expression

where expression denotes a separate expression describing the object whose type is checked. If the expression has a compatible or the same type as the type checked, the result of this operation is true, otherwise false. Thus, the result will be true if the expression has a verifiable type in one form or another. In the IS type statement, both are defined as compatible if they are the same type or if reference transformation, packaging or unpacking is provided.

Below is an example of using an IS operator:

Using SYSTEM; Namespace ConsoleApplication1 (Class Add () Class Sum: Add () Class Program (Static Void Main () (Add a \u003d New Add (); SUM S \u003d new sum (); if (a IS Add) Console.WriteLine ("variable A has type Add "); if (s IS SUM) Console.WriteLine (" The type of variable S is inherited from class AD "); Console.ReadLine ();)))

Operator as

Sometimes the type conversion is required during execution, but do not generate an exception if the outcome of this conversion will be unsuccessful, which is quite possible when the types are given. For this purpose, the AS operator has the following shape:

aS Type Expression

where expression denotes a separate expression that is converted to the specified type.

If the outcome of such a conversion turns out to be successful, then the link to the type is returned, and otherwise it is an empty link. The AS operator can only be used to convert links, identity, packaging, unpacking. 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 (); SUM S \u003d new sum (); // perform the type A \u003d S AD; IF (A! \u003d NULL) Console.WriteLine ("Conversion has been successful"); Else Console.Writeline ("Error converting"); console.ReadLine ();)))

The result of this program will be a successful conversion.

a \u003d (b\u003e 0) && (C + 1! \u003d D); Flag \u003d! (Status \u003d 0);

Table 14.5. Logic operators

Operator Description

! Not (logical inversion)

&& And (logical multiplication)

|| Or (logical addition)

Table 14.6. The results of the execution of operators and and or

Operand 1.

Operand 2.

Table 14.7. The results of the execution of the operator not

TypeOf receipt operator

Type receipt operatortypeof returns a string describing the type of operand data. Operand, the type of which you need to know are placed after this operator and enter into parentheses:

s \u003d Typeof ("STR");

As a result of the execution of this expression in the variable s it will be a string "String", denoting a string type.

All values \u200b\u200bthat the TypeOf operator can return are listed in Table. 14.8.

Table 14.8. Values \u200b\u200breturned by the Typeof operator

Data type

Return line

String

Numerical

Table 14.8 (end)

Data type

Return line

Logical

Compatibility and data type conversion

It is time to consider two more important issues: compatibility of data types and converting one type to another.

What happens if folded two numeric values? That's right - another numeric value. And if you fold the number and string? It is difficult to say ... Here JavaScript faces the problem of incompatibility of data types and tries to make these types compatible, transforming one of them to another. First, he tries to convert a row to the number and, if it manages, performs addition. In case of failure, the number will be transformed into the string, and the two rows obtained will be combined. For example, as a result of the implementation of the Web scenario from Listing 14.6, the value of the variable B when adding from the variable A will be converted into a numeric type; Thus, the variable C will contain a value 23.

Listing 14.6.

vAR A, B, C, D, E, F; a \u003d 11;

b \u003d "12"; c \u003d a + b;

d \u003d "javascript"; E \u003d 2;

But since the value of the variable D cannot be converted to a number, the value of E will be converted into the string, and the result - the value of F - will become equal

Logical values \u200b\u200bare converted either to numeric or in string, depending on the specific case. The True value will be converted to the number 1 or the string "1", and the value false - in 0 or "0". Conversely, the number 1 will be converted to True, and the number 0 is to False. Also in False will be transformed

null and undefined values.

Part III. Behavior Web pages. Web scenarios

It can be seen that JavaScript struggles to correctly perform even incorrectly written expressions. Sometimes it turns out, but more often everything works as planned, and in the end, the implementation of the Web scenario is interrupted in connection with the detection of an error completely in its other place, on an absolutely correct statement. Therefore, it is better to prevent such incidents.

Priority of operators

The last question we will look here are the priority of operators. As we remember, priority affects the order in which operators are performed in expression.

Let there be the following expression:

In this case, first to the value of the variable B will be added to C, and then 10 will be deducted from the amount. The operators of this expression have the same priority and therefore run strictly left to right.

Now consider such an expression:

Here, first will be performed multiplication of the value of C by 10, and only then the value b will be added to the result. The multiplication operator has a greater priority than the addition operator, so the order "strictly left to right" will be broken.

The lowest priority for assignment operators. That is why the expression itself first is calculated, and then its result is assigned to a variable.

IN in general, the basic principle of fulfilling all operators is as follows: first operators are performed with a higher priority, and only later operators with lower. Operators with the same priority are performed in the order of them (from left to right).

IN table. 14.9 The operators studied by us are listed in the order of their priorities.

Table 14.9. Priority of operators (in descending order)

Operators

Description

++ - - ~! Typeof.

Increment, Decrement, Sign Change, Logical Not, Definition

Multiplication, division, taking a balance

Addition and row merging, subtraction

Operators comparison

Logical I.

Chapter 14. Introduction to Web Programming. JavaScript language

Table 14.9 (end)

Operators

Description

Logical or

Conditional operator (see below)

= <оператор>=

Assignment, simple and complex

ATTENTION!

Remember this table. Incorrect procedure for performing operators can cause difficult errors in which externally absolutely correct expression gives an incorrect result.

But what if we need to break the usual order of execution of operators? We use brackets. With such an entry enclosed in brackets, operators are performed first:

a \u003d (b + c) * 10;

Here, first the addition of values \u200b\u200bof variables B and C will be completed, and then the resulting amount will be multiplied by 10.

Operators enclosed in brackets are also subject to priority. Therefore, multiple brackets are often used:

a \u003d ((B + C) * 10 - D) / 2 + 9;

Here operators will be performed in such a sequence:

1. Addition B and C.

2. Multiplying the amount received by 10.

3. Subtract D from the work.

4. Division of a difference for 2.

5. Adjament 9 to private.

If you remove brackets:

a \u003d b + C * 10 - D / 2 + 9;

the order of execution of operators will be:

1. Multiplication C and 10.

2. Dividing D to 2.

3. Addition B and works C and 10.

4. Subtraction from the received amount of private from divisiond 2.

5. Adjusted 9 to the obtained difference.

It turns out a completely different result, right?



Did you like the article? Share it