You get a bonus - 1 coin for daily activity. Now you have 1 coin

Type conversion for primitives

Lecture




  1. String conversion
  2. Numerical conversion
    1. Special values
  3. Logical transformation
  4. Total

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:

  1. String conversion.
  2. Numeric conversion
  3. Conversion to Boolean.

This article describes the transformation of primitive values, the objects are discussed further in the textbook.

String conversion

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

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:

  • Boolean values:
    1 alert( + true ); // 1
    2 alert( + false ); // 0
  • Comparing different types means numerical conversion:

    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 .

  • Another example:

    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 .

Special values

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.

Logical transformation

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) .

Note: the string "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!

An empty object or array is also 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 }
From the point of view of type conversion in JavaScript, this is completely normal. In case of equality - a numerical conversion, and in if - a logical one, that's all.

Total

There are three conversions in JavaScript:

  1. String: String(value) - in string context or when added to a string
  2. Numerical: Number(value) - in numerical context, including unary plus +value .
  3. Boolean: Boolean(value) - in a logical context, you can also make double NOT: !!value .

The comparison does not perform type conversion in the following cases:

  • When comparing objects. Two variables that are objects are equal only when they refer to the same object.
  • When comparing two lines. There is a separate comparison algorithm. But if at least one operand is not a string, then the values ​​will be given: true > "000" will become 1 > 0 .
  • When checking for equality with null and undefined . They are equal to each other, but not equal to anything else, this case is spelled out specifically in the specification.

Importance: 5

Think about the result of the expressions below. It's not just type conversions. When done - check with the decision.

01 "" + 1 + 0
02 "" - 1 + 0
03 true + false
04 6 / "3"
05 "2" * "3"
06 4 + 5 + "px"
07 "$" + 4 + 5
08 "4" - 2
09 "4px" - 2
10 7 / 0
11 parseInt( "09" )
12 " -9\n" + 5
13 " -9\n" - 5
14 5 && 2
15 2 && 5
16 5 || 0
17 0 || 5
18 null + 1
19 undefined + 1

Decision

01 "" + 1 + 0 = "10" // (1)
02 "" - 1 + 0 = -1 // (2)
03 true + false = 1
04 6 / "3" = 2
05 "2" * "3" = 6
06 4 + 5 + "px" = "9px"
07 "$" + 4 + 5 = "$45"
08 "4" - 2 = 2
09 "4px" - 2 = NaN
10 7 / 0 = Infinity
11 parseInt( "09" ) = "0" или "9" // (3)
12 " -9\n" + 5 = " -9\n5"
13 " -9\n" - 5 = -14
14 5 && 2 = 2
15 2 && 5 = 5
16 5 || 0 = 5
17 0 || 5 = 5
18 null + 1 = 1 // (4)
19 undefined + 1 = NaN // (5)

  1. The operator "+" in this case adds 1 as a string, and then 0 .
  2. The operator "-" works only with numbers, so that it immediately leads "" to 0 .
  3. In some browsers, a parseInt without a second argument interprets 09 as an octal number.
  4. null when numeric conversion becomes 0
  5. undefined in numerical conversion becomes NaN
[Open for
created: 2014-10-07
updated: 2024-11-14
256



Rating 9 of 10. count vote: 2
Are you satisfied?:



Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Scripting client side JavaScript, jqvery, BackBone

Terms: Scripting client side JavaScript, jqvery, BackBone