Lecture
The type conversion system in JavaScript is very simple, but different from other languages. Therefore, it often serves as a stumbling block for programmers coming from other languages.
There are three transformations:
This article describes the transformation of primitive values, the objects are discussed further in the textbook.
String conversion occurs when you want to represent something as a string. For example, it is produced by the alert function.
1 | var a = true ; |
2 |
3 | alert(a); // "true" |
You can also perform the conversion by explicitly calling String(val) :
1 | alert( String( null ) === "null" ); // true |
Also for the explicit conversion is used the operator "+" , in which one of the arguments is a string. In this case, it leads to a string and another argument, for example:
1 | alert( true + "test" ); // "truetest" |
2 | alert( "123" + undefined ); // "123undefined" |
Numerical conversion occurs in mathematical functions and expressions, as well as when comparing data of various types (except comparisons === !== ).
To convert to a number, you can call Number(val) explicitly, or, in short, put the unary plus "+" operator before the expression:
var a = + "\n123\n" ; // 123 |
var a = Number( "\n123\n" ); // 123, тот же эффект |
| Value | Transformed into ... |
|---|---|
undefined | NaN |
null | 0 |
true / false | 1 / 0 |
| Line | Spaces at the edges are trimmed. Further, if an empty string remains, then 0 . From a non-empty string, a number is “read”; if an error occurs, the result is: NaN . |
Examples:
1 | alert( + true ); // 1 |
2 | alert( + false ); // 0 |
1 | alert( "\n0\n" == 0 ); // true |
In this case, the string "\n0\n" converted to a number - initial and final spaces are ignored, it turns out 0 .
1 | alert( "\n" == false ); |
Here the comparison == again leads both parts to a number. Both on the left and on the right is 0 .
For a similar reason, the equality "1" == true .
Let's look at the behavior of special values more closely.
Intuitively, null/undefined values are associated with zero, but behave differently during transformations.
Special values are converted to a number like this:
| Value | Transformed into ... |
|---|---|
undefined | NaN |
null | 0 |
This transformation is carried out with arithmetic operations and comparisons > >= < <= , but not with equality == . The equality check algorithm for these values is spelled out separately in the specification (clause 11.9.3). It assumes that null and undefined are equal to "==" between each other, but these values are not equal to any other value.
This leads to funny consequences.
For example, null does not obey the laws of mathematics - it is “greater or equal to zero”: null>=0 , but no more and is not equal to:
1 | alert( null >= 0); // true, т.к. null преобразуется к 0 |
2 | alert( null > 0); // false (не больше), т.к. null преобразуется к 0 |
3 | alert( null == 0 ); // false (и не равен!), т.к. == рассматривает null особо. |
The value of undefined generally out of comparison:
1 | alert( undefined > 0); // false, т.к. undefined -> NaN |
2 | alert( undefined == 0); // false, т.к. это undefined (без преобразования) |
3 | alert( undefined < 0); // false, т.к. undefined -> NaN |
For more obvious code operation and in order to avoid errors, it is better not to allow special values to participate in comparisons > >= < <= .
Use variable numbers in such cases, or cite numbers explicitly.
Conversion to true/false occurs in a logical context, such as if(obj) , while(obj) and when applying logical operators.
All values that are intuitively “empty” become false . There are several: 0 , the empty string, null , undefined and NaN .
The rest, including any objects - true .
Full conversion table:
| Value | Transformed into ... |
|---|---|
undefined , null | false |
| Numbers | All true , except 0 , NaN - false . |
| Strings | All true , except for the empty string "" - false |
| Objects | Always true |
For explicit conversion, double logical negation is used !!value or Boolean(value) .
"0" becomes true Unlike many programming languages (such as PHP), the "0" in JavaScript is true , as is the string of spaces:
1 | alert( !! "0" ); // true |
2 | alert( !! " " ); // любые непустые строки, даже из пробелов - true! |
true Also, unlike some other programming languages, the empty object {} or array [] is true :
1 | if ( {} ) { |
2 | alert( "{} -> true" ); |
3 | } |
4 |
5 | if ( [] ) { |
6 | alert( "[] -> true" ); |
7 | } |
The logical transformation is interesting in how it is combined with the numerical one.
Two values can be equal, but one of them in a logical context is true , the other is false .
For example, the equalities in the following example are true, as the numerical conversion occurs:
1 | alert( 0 == "\n0\n" ); // true |
2 | alert( false == " " ); // true |
... And in a logical context, the left side will give false , the right - true :
1 | if ( "\n0\n" ) { |
2 | alert( "true, совсем не как 0!" ); |
3 | } |
if - a logical one, that's all. There are three conversions in JavaScript:
String(value) - in string context or when added to a string Number(value) - in numerical context, including unary plus +value . Boolean(value) - in a logical context, you can also make double NOT: !!value . The comparison does not perform type conversion in the following cases:
true > "000" will become 1 > 0 . null and undefined . They are equal to each other, but not equal to anything else, this case is spelled out specifically in the specification.
Comments
To leave a comment
Scripting client side JavaScript, jqvery, BackBone
Terms: Scripting client side JavaScript, jqvery, BackBone