Casting data types in javascript. JavaScript: Data Type Conversion


JavaScript provides several built-in data types. In addition to these, this article covers virtual types in jQuery such as selectors, extended pseudotypes like events, and all kinds of functions.

It's best if you try most of the examples below. This can be easily done by simply copying these examples into the Firebug console, a Firefox browser extension.

Whenever the examples perform operations in a Boolean context (such as comparisons), it is important to know how each data type behaves in that context:

Var x = "" if (x) console.log("x defaulted to true") else console.log("x defaulted to false")

In this case, "x equals false" will be printed.

To reduce the length of examples, the negation operator is used to show boolean context:

X // true

jQuery Data Types

  1. Strings
    • Built-in methods for strings
    • length property
    • Boolean context
  2. Numbers
    • Boolean context
    • Parsing Numbers
    • Numbers to Strings
    • NaN and Infinity
    • Integer
    • Float
  3. Boolean type
  4. Objects
    • Dot Notation
    • Array Notation
    • Iteration
    • Boolean default
    • Prototype
  5. Options
  6. Arrays
    • Iteration
    • Boolean Default
    • Array Notation
  7. Functions
    • Arguments
    • Context, Call and Apply
    • Area of ​​visibility
    • Closures
    • Proxy Pattern
  8. Callback functions
  9. Selectors
  10. Events
  11. Elements
  12. jQuery type
  13. XMLHttpRequest type

Strings

"This is a JavaScript string!" "And this is also a line!"

A string in JavaScript is an immutable object that contains zero, one, or more characters.

The type of strings is "string". You can find out the type of a string like this:

Typeof "some string"; // "string"

Using quotes in strings

A string can be defined using single or double quotes. You are free to use single quotes inside a string enclosed in double quotes and vice versa. To use double quotes inside double-quoted strings, they must be escaped with a backslash \ . This also applies to single quotes.

"You make me sad." "Holy "cranking" moses!" " home" "home"

Built-in methods for strings

JavaScript has several built-in methods for manipulating strings, the result of which can be either a string or, for example, an array:

"hello".charAt(0) // "h" - getting the character at the desired position in the string "hello".toUpperCase() // "HELLO" - converting the string to uppercase "Hello".toLowerCase() // "hello" - converting a string to lowercase "hello".replace(/e|o/g, "x") // "hxllx" - replacing part of a string with a substring using the regular expression pattern "1,2,3".split(", ") // ["1", "2", "3"] - splitting a string into an array by a specific substring

length property

Strings have a length property that specifies the length of the string.

"Hello".length // 5 "".length // 0

Boolean context

An empty string evaluates to false:

!"" // true ! "hello" // false ! "true" // false !new Boolean(false) // false

Numbers

12 3.543

Numbers in JavaScript are in 64-bit double precision format according to the IEEE 754 standard. They are also immutable. To work with numbers, all operators are available, the same as in the C language (+, -, *, /, %, =, +=, -=, *=, /=, ++, --).

The type for numbers is "number". You can check the type of numbers like this:

Typeof 12 // "number" typeof 3.543 // "number"

Boolean context

If the number is zero, then it is equal to false:

0 // true !1 // false !-1 // false

Because numbers are implemented in double precision format, the output of the following example is not incorrect:

0.1 + 0.2 // 0.30000000000000004

Math object

JavaScript provides functions for working with numbers in a Math object:

Math.PI // 3.141592653589793 Math.cos(Math.PI) // -1

Convert to numbers

The parseInt and parseFloat functions convert strings to numbers. Both functions perform implicit conversion if the number system is not specified:

ParseInt("123") = 123 (implicit decimal conversion) parseInt("010") = 8 (implicit octal conversion) parseInt("0xCAFE") = 51966 (implicit hex conversion) parseInt("010", 10) = 10 (explicit decimal conversion with radix 10) parseInt("11", 2) = 3 (explicit binary conversion) parseFloat("10.10") = 10.1

Converting numbers to strings

If you add numbers to a string using the "+" operation, the result will always be a string. To perform calculations before adding a number to a string, be sure to enclose the calculations in parentheses:

"" + 1 + 2; // "12" "" + (1 + 2); // "3" "" + 0.0000001; // "1e-7" parseInt(0.0000001); // 1 (note!)

You can also use the JavaScript String class, which converts the passed value to a string:

String(1) + String(2); // "12" String(1 + 2); // "3"

NaN and Infinity types

Converting values ​​that are not numbers results in NaN. The isNaN function determines whether the value passed to it is equal to NaN:

ParseInt("hello", 10) // NaN isNaN(parseInt("hello", 10)) // true

Dividing by zero gives the result Infinity:

1 / 0 // Infinity

Both the NaN and Infinity value are of type "number":

Typeof NaN // "number" typeof Infinity // "number"

Please note that comparison of NaN values ​​occurs in a non-standard way:

NaN == NaN // false (!)

Infinity == Infinity // true

Integer type

Integer is an integer type.

Float type

Float is a floating point number type.

Boolean type

A boolean type in JavaScript can be true or false:

If (true) console.log("always!") if (false) console.log("never!")

For example, a boolean type looks like this when setting the settings when connecting jQuery plugins:

$("...").somePlugin(( hideOnStartup: true, onlyOnce: false ));

Objects

Everything in JavaScript is an object. The easiest way to create an object is:

Var x = (); var y = ( name: "Pete", age: 15 );

The type for objects is "object":

Typeof() // "object"

Object properties

You can change and get properties of an object using dot notation:

Y.name // "Pete" y.age // 15 x.name = y.name + " Pan" // "Pete Pan" x.age = y.age + 1 // 16

You can also use the object as an array:

Var operations = ( increase: "++", decrease: "--" ) var operation = "increase"; operations // "++"; operations["multiply"] = "*"; // "*"

Iterations on objects

Iterating over objects is very easy using the for-in loop operator:

Var obj = ( name: "Pete", age: 15 ); for(key in obj) ( alert("key is "++", value is "+obj); )

jQuery provides a function

to iterate over object properties or array elements:

JQuery.each(obj, function(key, value) ( ​​console.log("key", key, "value", value); ));

Boolean context

An object, whether it has properties or not, is always true:

!() // false

Prototypes

All objects have a prototype property. Whenever the interpreter looks for a property on an object, it also checks its prototype. In jQuery, this mechanism is widely used to add methods to instances of jQuery objects.

Var form = $("#myform"); form.clearForm; // undefined form.fn.clearForm = function() ( return this.find(":input").each(function() ( this.value = ""; )).end(); ); form.clearForm() // can be applied to all instances of jQuery objects since a new method was added to the prototype

JavaScript is an untyped language (more precisely, weakly typed or dynamically typed). This means that we should not specify the type of a variable when declaring it. Being untyped gives JavaScript the flexibility and simplicity favored by a scripting language (though these features come at the cost of a lack of rigor, which is important for longer and more complex programs, which are often written in stricter languages ​​such as C or Java). An important feature of flexible work with data types in JavaScript is the automatic data conversions performed by the interpreter. For example, if you pass a number to the document.write() method, JavaScript will automatically convert it to its equivalent string representation. Likewise, by testing a string value in the condition of an if statement, JavaScript automatically converts that string to a boolean value—false if the string is empty, true otherwise.

The basic rule is that when a value of one type is encountered in a context that requires a value of some other type, JavaScript will automatically attempt to convert the value in the required manner. Therefore, for example, in a context involving a boolean variable, a number is converted to a boolean value.

An object in a string context is converted to a string. JavaScript tries to convert a string in a numeric context to a number.

Object-elementary type conversions
For example, in a Boolean context, all of the following objects evaluate to true:

New Boolean(false) // The internal value is false, but the object
// converts to true
new Number(0)
new String("")
new Array()

Converting objects to numbers begins by calling the valueOf() method of that object. Most objects inherit the standard valueOf() method of the Object class, which simply returns the object itself. Since the standard valueOf() method does not return a primitive value, JavaScript then attempts to convert the object to a number by calling its toString() method and converting the resulting string to a number. For arrays this leads to interesting results. Recall that the toString() method converts array elements to strings and then returns the result of concatenating those strings with commas in between. Therefore, an array with no elements is converted to an empty string, which is converted to 0! Additionally, if the array consists of one element, the number n, then the array is converted to a string representation of that number, which is then converted back to the number n itself.

If the array contains more than one element, or if its only element is not a number, the array is converted to NaN. In JavaScript, the context is not always clearly defined! The + operator and the comparison operators (and >=) work with both numbers and strings, so when an object is used with one of these operators, it is unclear whether it should convert to a number or a string. In most cases, JavaScript first tries to convert the object by calling the valueOf() method. If this method returns a primitive value (usually a number), that value is used. However, often valueOf() simply returns the object without conversion; in this case, JavaScript then tries to convert the object to a string by calling the toString() method. There is only one exception to this conversion rule: when a Date object is used with the + operator, the conversion is performed using the toString() method. This exception exists because Date has both a toString() method and a valueOf() method. When using Date with the + operator, you almost always need to perform string concatenation. But when Date is involved in comparison operations, it almost always requires a numeric comparison to be performed in order to determine which of two points in time preceded the other.

Most objects either do not have a valueOf() method, or the method does not return useful results.

When the + operator is applied to an object, string concatenation rather than addition usually occurs. When a comparison operator is applied to an object, it is typically a string comparison rather than a numeric comparison.

An object that defines a special valueOf() method may behave differently. By defining a valueOf() method that returns a number, you can apply arithmetic and other operators to your object, but adding your object to a string will not work as expected: the toString() method is no longer called and the concatenation involves the string representation of the number returned by the method valueOf().

Finally, remember that the valueOf() method is not called toNumber(); strictly speaking, its job is to convert the object into a meaningful primitive value, so some objects may have valueOf() methods that return strings.

Explicit type conversions
Java-Script does not define a conversion operator like C, C++, and Java, but it provides similar facilities. In JavaScript 1.1 (and the ECMA-262 standard), Number(), Boolean(), String(), and Object() can be called not only as constructors, but also as functions. When called in this way, these functions attempt to convert their
arguments to the appropriate type. For example, you can convert any x value to a string using String(x) and any y value to an object using Object(y).

There are several other techniques that can be useful for performing explicit type conversions. To convert a value to a string, concatenate it with an empty string:

Var x_as_string = x + "";

To convert a value to a number, subtract zero from it:

Var x_as_number = x - 0;

You can force a value to be converted to a boolean using the! operator applied twice:

Var x_as_boolean = !!x;

Because of JavaScript's tendency to automatically convert data to the currently needed type, explicit conversions are usually not required. However, occasionally they turn out to be useful, and can be used to make the program clearer and more accurate.

Converting numbers to strings
Converting numbers to strings is done in JavaScript perhaps more often than others. Although this is usually done automatically, there are several useful ways to make this kind of conversion explicit. We have already seen two:

Var string_value = String(number); // Using the String() constructor
// as a function
var string_value = number + ""; // Concatenate with an empty string

Another possibility is provided by the toString() method:

String_value = number.toString();

The toString() method of a Number object (elementary numeric values ​​are converted to Number objects, so you can call this method) takes an optional argument that specifies the radix to which the conversion will be performed. If no argument is specified, the conversion is performed in base 10. But you can convert numbers in other bases (between 2 and 36). For example:

Var n = 17;
binary_string = n.toString(2); // Equal to "10001"
octal_string = "0" + n.toString(8); // Equal to "021"
hex_string = "0x" + n.toString(16); // Equal to "0x11"

A drawback of JavaScript versions prior to version 1.5 is that there is no standard way to specify the number of decimal places in the string resulting from a number conversion, or to require the use of scientific notation. This can make it difficult to display numbers that have traditional formats, such as monetary values.

ECMAScript v3 and JavaScript 1.5 get around this obstacle by adding three new methods for converting a number to a string to the Number class. The toFixed() method converts a number to a string and outputs the specified number of digits after the decimal point, without using scientific notation. The toExponential() method converts a number to a string, writing it in exponential notation with one digit before the decimal point and the specified number of digits after it. The toPrecision() method outputs a number using the specified number of significant digits. If this number of significant digits is not enough to print the whole part of the number, it is written in scientific notation. Note that all three methods correctly round the final digits of the resulting string. Look at the following examples:

Var n = 123456.789;
n.toFixed(0); // "123457"
n.toFixed(2); // "123456.79"
n.toExponential(1); // "1.2e+5"
n.toExponential(3); // "1.235e+5"
n.toPrecision(4); // "1.235e+5"
n.toPrecision(7); // "123456.8"

Converting strings to numbers
We have seen that in a numeric context, strings representing numbers are automatically converted to real numbers. As shown above, this conversion can be made explicit:

Var number = Number(string_value);
var number = string_value - 0;

This transformation is inconvenient due to its excessive severity. It only works with decimal numbers, and although the conversion allows leading and trailing spaces, it does not allow any non-whitespace characters after the number in the string. For more flexible transformations, you can use the parseInt() and parseFloat() functions. These functions convert and return any number present at the beginning of the string, ignoring any trailing non-numeric characters. The parseInt() function only handles integers, while parseFloat() handles both integers and floats. If the string starts with "0x" or "0X", parseInt() interprets it as a hexadecimal number. For example:

ParseInt("3 blind mice"); // Returns 3
parseFloat("3.14 meters"); // Returns 3.14
parseInt("12.34"); // Returns 12
parseInt("0xFF"); // Returns 255

The parseInt() function can have a second argument indicating the radix of the number being processed. Valid values ​​are from 2 to 36. For example:

ParseInt("11", 2); // Returns 3 (1*2 + 1)
parseInt("ff", 16); // Returns 255 (15*16 + 15)
parseInt("zz", 36); // Returns 1295 (35*36 + 35)
parseInt("077", 8); // Returns 63 (7*8 + 7)
parseInt("077", 10); // Returns 77 (7*10 + 7)

If parseInt() and parseFloat() cannot convert the specified string to a number, they return NaN.

ParseInt("eleven"); // Return NaN
parseFloat("$72.47"); // Return NaN

JavaScript has 2 built-in functions for converting strings to numbers: parseFloat() and parseInt() .

parseFloat() takes as an argument a string to be converted to a numeric type and returns a float number. The number must appear at the beginning of the line. If there are any other characters in the line after the number, they are cut off. The fractional part of a number must be written separated by a dot (a comma is not perceived as a separator). If parseFloat() cannot convert the string, it returns NaN.

The function can also process “the number n multiplied by 10 to the x power,” which in programming is usually written with the letter E, for example: 0.5E6 or 0.5E+6. The degree can also be negative: 0.5E-6, which is equal to 0.5*10^-6 or 0.5/1000000.

ParseFloat(""3.78kg"") // 3.78 parseFloat(""kg33"") // NaN parseFloat(""0004.111"") // 4.111 parseFloat(""0x66"") // 0 parseFloat("". 5"") // 0.5 parseFloat(""-.5"") // -0.5 parseFloat(""0.5e6"") // 500000 parseFloat(""0.03E+2"") // 3 parseFloat(" "3E-4"") // 0.0003 parseFloat(""-3E-4"") // -0.0003

The parseInt(string[, radix]) function takes a string as its first argument, parses it and returns an integer (type integer). The function attempts to analyze the number system in which the number in the source string is written (for example, decimal, octal or hexadecimal - but not only these). You can also specify the number system explicitly by passing it as the second parameter radix. The radix parameter can take any number from 2 to 36 (in systems higher than 10, letters of the English alphabet are used, from A to Z).

The function does not handle numbers like 1.5e6 like parseFloat() .

Please read the examples below so as not to stumble upon the pitfalls hidden in the operation of the parseInt() function.

ParseInt(""25"") // 25 parseInt(""-25"") // -25 parseInt(""45.12"") // 45 parseInt(""045"",10) // 45 parseInt( ""70"",8) // 56 (70 in octal is 56 in decimal) parseInt(""070"") // 56 (IMPORTANT!!! zero first will cause the function to parse the string as an octal number) parseInt(" "88"",8) // NaN (there is no digit 8 in the octal system) parseInt(""a1"") // NaN (IMPORTANT!!! The default function does not treat the number as hexadecimal if it is not added at the beginning lines 0x) parseInt(""a1"",16) // 161 (the number system is explicitly specified here) parseInt(""0xa1"") // 161 (correct hexadecimal number format, you don't have to specify the second parameter) parseInt( ""099"") // 0 (IMPORTANT!!! The number is treated as octal, but contains invalid characters) parseInt(""0.5e6"") // 0 (IMPORTANT!!! does not work like parseFloat) parseInt("" ZZ"",36) // 1295 parseInt(""-FF"") // NaN parseInt(""-FF"",16) // -255

If you are parsing user input from a text field, always use parseInt() along with a second radix parameter to protect your code from unexpected results.

JavaScript has 2 built-in functions for converting strings to numbers: parseFloat() and parseInt() .

parseFloat() takes as an argument a string to be converted to a numeric type and returns a float number. The number must appear at the beginning of the line. If there are any other characters in the line after the number, they are cut off. The fractional part of a number must be written separated by a dot (a comma is not perceived as a separator). If parseFloat() cannot convert the string, it returns NaN.

The function can also process “the number n multiplied by 10 to the x power,” which in programming is usually written with the letter E, for example: 0.5E6 or 0.5E+6. The degree can also be negative: 0.5E-6, which is equal to 0.5*10^-6 or 0.5/1000000.

ParseFloat(""3.78kg"") // 3.78 parseFloat(""kg33"") // NaN parseFloat(""0004.111"") // 4.111 parseFloat(""0x66"") // 0 parseFloat("". 5"") // 0.5 parseFloat(""-.5"") // -0.5 parseFloat(""0.5e6"") // 500000 parseFloat(""0.03E+2"") // 3 parseFloat(" "3E-4"") // 0.0003 parseFloat(""-3E-4"") // -0.0003

The parseInt(string[, radix]) function takes a string as its first argument, parses it and returns an integer (type integer). The function attempts to analyze the number system in which the number in the source string is written (for example, decimal, octal or hexadecimal - but not only these). You can also specify the number system explicitly by passing it as the second parameter radix. The radix parameter can take any number from 2 to 36 (in systems higher than 10, letters of the English alphabet are used, from A to Z).

The function does not handle numbers like 1.5e6 like parseFloat() .

Please read the examples below so as not to stumble upon the pitfalls hidden in the operation of the parseInt() function.

ParseInt(""25"") // 25 parseInt(""-25"") // -25 parseInt(""45.12"") // 45 parseInt(""045"",10) // 45 parseInt( ""70"",8) // 56 (70 in octal is 56 in decimal) parseInt(""070"") // 56 (IMPORTANT!!! zero first will cause the function to parse the string as an octal number) parseInt(" "88"",8) // NaN (there is no digit 8 in the octal system) parseInt(""a1"") // NaN (IMPORTANT!!! The default function does not treat the number as hexadecimal if it is not added at the beginning lines 0x) parseInt(""a1"",16) // 161 (the number system is explicitly specified here) parseInt(""0xa1"") // 161 (correct hexadecimal number format, you don't have to specify the second parameter) parseInt( ""099"") // 0 (IMPORTANT!!! The number is treated as octal, but contains invalid characters) parseInt(""0.5e6"") // 0 (IMPORTANT!!! does not work like parseFloat) parseInt("" ZZ"",36) // 1295 parseInt(""-FF"") // NaN parseInt(""-FF"",16) // -255

If you are parsing user input from a text field, always use parseInt() along with a second radix parameter to protect your code from unexpected results.

In JavaScript, values ​​can be converted quite freely (explicitly and implicitly) from one type to another. For example, if an operator expects to receive a value of a certain type, and is passed a value of another type, the interpreter will automatically try to perform conversions to the desired type:

Console.log(10 + " machines"); // "10 cars". The number is implicitly converted to a string console.log("7" * "4"); // 28. Both strings are implicitly converted to numbers

Implicit conversion- this is when the interpreter automatically performs type conversion, that is, without the participation of the programmer. Explicit conversion- this is when the conversion is performed by the programmer himself. Explicit conversion is also called type casting:

Console.log("7" * "4"); // 28. Implicit conversion console.log(Number("7") * Number("4")); // 28. Explicit conversion

The table below describes how JavaScript converts values ​​from one type to another. Empty cells correspond to situations where no conversion is required:

Meaning Convert to:
String Number Boolean An object
undefined
null
"undefined"
"null"
NaN
0
false
false
error typeError
error typeError
true
false
"true"
"false"
1
0
new Boolean(true)
new Boolean(false)
"" (empty line)
"1.2"
"one"
"-10"
"+10"
"011"
"0xff"
0
1.2
NaN
-10
10
11
255
false
true
true
true
true
true
true
new String("")
new String("1.2")
new String("one")
new String("-10")
new String("+10")
new String("011")
new String("0xff")
0
-0
NaN
Infinity
-Infinity
3
"0"
"0"
"NaN"
"Infinity"
"-Infinity"
"3"
false
false
false
true
true
true
new Number(0)
new Number(-0)
new Number(NaN)
new Number(Infinity)
new Number(-Infinity)
new Number(3)
() (any object)

(empty array)
(1 numeric element)
arr (any other array)
function()() (any function)

see Converting Objects

""
"9"
see Converting Objects
see Converting Objects

see Converting Objects
0
9
NaN
NaN
true

true
true
true
true

For explicit conversion to simple types, the following functions are used: Boolean(), Number(), String(). For implicit conversion, the interpreter uses the same functions that are used for explicit conversion.

For explicit conversion, you can use operators instead of functions. For example, if one of the operands of the + operator is a string, then the other operand is also converted to a string. The unary + operator converts its operand to a number. Unary operator! converts the operand to a boolean value and inverts it. All this became the reason for the emergence of the following unique methods of type conversion that can be found in practice:

X + "" // Same as String(x) +x // Same as Number(x). You can also see x - 0 !!x // Same as Boolean(x)

Convert to numbers

The Number() function converts values ​​according to the following rules:

  • The boolean values ​​true and false are converted to 1 and 0 respectively.
  • The numbers are returned unchanged.
  • The value null is converted to 0 .
  • The undefined value is converted to NaN.

There are special rules for strings:

  • If a string contains only digits with a leading + or - sign, or without a sign, it is always converted to an integer decimal number. Leading zeros are ignored, for example "0011" is converted to 11.
  • If the string is a floating-point number with a leading + or - or unsigned sign, it is converted to the corresponding floating-point number (leading zeros are also ignored).
  • If the string is a hexadecimal number, it is converted to the corresponding decimal integer.
  • If the string is empty, it is converted to 0.
  • If the string contains something different from the previous options, it is converted to NaN.
  • The valueOf() method is called on objects, and the value it returns is automatically converted according to the previous rules. If this conversion results in NaN , the toString() method is called and the rules for converting strings to numbers are applied.

The unary operators + and - follow the same rules as the Number() function.

Converting to Boolean Values

The Boolean() function converts a value to its Boolean equivalent:

  • The following values ​​are converted to false: undefined , null , 0 , -0 , NaN , "" .
  • False is returned unchanged.
  • All other values ​​are converted to true .

Convert to strings

The String() function converts values ​​according to the following rules:

  • For all values ​​other than null and undefined, the toString() method is automatically called and a string representation of the value is returned.
  • For null, the string "null" is returned.
  • For the value undefined, the string "undefined" is returned.

Converting Simple Types to Objects

To convert simple values ​​into objects, the Boolean() , Number() , String() constructors are used:

Var oNum = new Number(3); var oStr = new String("1.2"); var oBool = new Boolean(true); alert(typeof oNum); // "object" alert(typeof oStr); // "object" alert(typeof oBool); // "object"

Converting objects to simple values

All objects inherit two conversion methods: toString() and valueOf() .

The toString() method returns the string representation of the object. By default it doesn't return anything interesting:

Alert((x: 1).toString()); // ""

Some types have more specialized versions of the toString() method. For example, the toString() method on an array converts all its elements to strings and then concatenates them into one string, inserting commas between them:

Alert(.toString()); // "1,2,3"

The purpose of the valueOf() method is less clearly defined: it is supposed to convert an object to the simple value that represents it, if such a value exists. Objects are inherently composite values, and most objects cannot be represented as a single simple value, so by default the valueOf() method returns a reference to it rather than a simple value:

Alert(typeof (x:2).valueOf()); // "object"

When converting an object to a string, the JavaScript interpreter does the following:

  • If an object has a toString() method, the interpreter calls it. If it returns a simple value, the interpreter converts the value to a string (if it is not a string) and returns the result of the conversion.
  • If the object does not have a toString() method or the method does not return a simple value, then the interpreter checks for the presence of a valueOf() method. If this method is defined, the interpreter calls it. If it returns a simple value, the interpreter converts that value to a string (if it is not a string) and returns the result of the conversion.

When converting an object to a number, the interpreter does the same thing, but tries the valueOf() method first:

  • If an object has a valueOf() method that returns a simple value, the interpreter converts (if necessary) that value to a number and returns the result.
  • If the object does not have a valueOf() method or the method does not return a simple value, then the interpreter checks for the presence of a toString() method. If the object has a toString() method that returns a simple value, the interpreter performs the conversion and returns the resulting value.
  • Otherwise, the interpreter concludes that neither toString() nor valueOf() can obtain a simple value and raises a TypeError.

The toString() and valueOf() methods are read/write, so you can override them and explicitly specify what will be returned when converting:

Var obj = (); obj.toString = function() ( return "object"; ); alert("This is " + obj); // "This is an object"







2024 gtavrl.ru.