1/21/2014

Conversion, toString and valueOf | JavaScript Tutorial
Log in

JavaScript Tutorial
Home » Tutorial » JavaScript: from the Ground to Closures » Mastering data types
‹ Array Four scents of "this" › Tutorial

JavaScript: from the Ground to Closures
JavaScript: from the Ground to Closures Javascript and related technologies First Steps Functions: declarations and expressions Mastering data types
Mastering data types String Number, Math Objects Array Conversion, toString and valueOf

Conversion, toString and valueOf
Ilya Kantor

1. String conversion 1. The algorithm of Object to String conversion 2. Custom t o S t r i n g 2. Numeric conversion 1. Custom v a l u e O fexample 3. Conversion in equality/comparison tests 4. Boolean context 5. Summary Objects in JavaScript can be converted to primitives in three contexts: 1. Numeric 2. String 3. Boolean

Like

3

Four scents of "this" Type detection Function arguments Static variables and methods Scopes and Closures Decorators

Understanding the way conversion works helps to evade possible pitfalls and write cleaner code.

String conversion
String conversion happens when a string representation of an object is required. For example, in a l e r t ( o b j )does it to output o b j :
Run!

Document and Events Object Oriented Programming Timing Frames and windows Regular expressions in JavaScript Advanced and Extra stuff

1 v a ro b j={n a m e :' J o h n '} 2 3 a l e r t ( o b j )/ /[ o b j e c tO b j e c t ] The explicit conversion is also possible: S t r i n g ( o b j ) .

The algorithm of Object to String conversion
1. If t o S t r i n gmethod exists and returns a primitive, then return it. Execution normally stops here, because t o S t r i n gexists on all objects by default. 2. If v a l u e O fmethod exists and returns a primitive, then return it. 3. Otherwise, throw an exception. Again, normally all objects have t o S t r i n g . Built-in objects have their own t o S t r i n gimplementations:
Run!

Donate Donate to this project

1 a l e r t ({ k e y :' v a l u e ' })/ /t o S t r i n gf o rO b j e c t so u t p u t s :[ o b j e c tO b j e c t ] 2 a l e r t ([ 1 , 2 ]) / /t o S t r i n gf o rA r r a y sl i s t se l e m e n t s" 1 , 2 " 3 a l e r t (n e wD a t e) / /t o S t r i n gf o rD a t e so u t p u t st h ed a t ea sas t r i n g

Custom t o S t r i n g
For our objects, we can implement a custom t o S t r i n g :
Run!

0 1 v a ru s e r={ 0 2 0 3 f i r s t N a m e :' J o h n ' , 0 4 0 5 t o S t r i n g :f u n c t i o n ( ){ 0 6 r e t u r n' U s e r'+t h i s . f i r s t N a m e 0 7 } 0 8 } 0 9 1 0 a l e r t (u s e r) / /U s e rJ o h n

Numeric conversion
There is another conversion in JavaScript, not as wide known as t o S t r i n g , but internally it is called much more often.

http://javascript.info/tutorial/object-conversion

1/5

It means that numeric conversion is handled by t o S t r i n g . but there is no limitation on its concrete type. 3 ' For historical reasons. 2 . 3 ]>' 1 . including arithmetic operators: + o b j . Because of that. 0 4 0 5 t o S t r i n g :f u n c t i o n ( ){ 0 6 r e t u r nt h i s . Otherwise. 3 ])/ /[ 1 . n u m 0 7 } 0 8 } 0 9 1 0 a l e r t (r o o m/3) / /2 5 9 Numeric conversion and being a number Numeric conversion does not mean. 2 . but enforce a number. and also nonstrict equality when both arguments are objects. It is true only if both arguments reference the same object. 2. but no v a l u e O f . If v a l u e O fmethod exists and returns a primitive.info/tutorial/object-conversion 2/5 . 2 . 2 . Among built-in objects. D a t esupports both numeric and string conversion: Run! 1 a l e r t (n e wD a t e ( ))/ /T h ed a t ei nh u m a n r e a d a b l ef o r m 2 a l e r t (+ n e wD a t e ( ))/ /M i c r o s e c o n d st i l l1J a n1 9 7 0 But most objects do not have v a l u e O f . 3 '>n o tan u m b e r Conversion in equality/comparison tests http://javascript.i s N a N ( o b j ) . then return it. Other mathematical functions not only perform the numeric conversion. The algorithm of numeric conversion: 1. throw an exception. Otherwise. In comparisons. that a number is returned. 2 . It must return a primitive. n e wD a t e+' 'also returns a string representation of D a t eeven though n e wD a t ehas v a l u e O f . then return it. The exceptions are the string equality = = = . v a l u e O f ( ) . 3. s i n ( o b j ) . That’s an exception. toString and valueOf | JavaScript Tutorial In functions which needs a number: for example M a t h . n u m 0 7 } 0 8 } 0 9 1 0 a l e r t (+ r o o m) / /7 7 7 If there is a custom t o S t r i n g . if t o S t r i n gmethod exists and returns a primitive. 3 ] a l e r t (a r r+' ') / /f i r s tt r i e sa r r .1/21/2014 Numeric conversion is performed in two main cases: Conversion. the interpreter will use it for numeric conversion: Run! 0 1 v a rr o o m={ 0 2 0 3 n u m :7 7 7 . the unary addition + a r rwould give N a N : Run! 1 a l e r t (+ [ 1 . like o b j= =' J o h n ' . not primitives: o b j 1= =o b j 2 . Custom v a l u e O fexample The magic method v a l u e O fcan be customized. a good way to convert an object to a string is the binary addition: Run! 1 2 3 4 5 v a ra r r=[ 1 . For example. just like t o S t r i n g : Run! 0 1 v a rr o o m={ 0 2 0 3 n u m :7 7 7 . because it doesn’t do any type conversion. The explicit conversion can also be done with N u m b e r ( o b j ) .b u ta r r a y sh a v en ov a l u e O f / /s oa r r . 0 4 0 5 v a l u e O f :f u n c t i o n ( ){ 0 6 r e t u r nt h i s . t o S t r i n g ( )i sc a l l e da n dr e t u r n sal i s to fe l e m e n t s : ' 1 .

Of course. If happens in boolean context.t r u e .} There will no be conversion in equity check for two objects: o b j 1= =o b j 2is true only if they refer to the same object. A way to frighten Java programmers. The equality converts an object only if it is compared against a primitive: i f( o b j= =t r u e ){.N a Nbecome f a l s e . because they equal 0 . . but in boolean context ais t r u eand bis f a l s e . toString and valueOf | JavaScript Tutorial Non-strict equality and comparisons use numeric context. let’s try to get a boolean out of zero: Run! http://javascript. " "becomes f a l s e . To convert a value to boolean. .n u l l N u m b e r S t r i n g O b j e c t Converted to… no conversion f a l s e 0 .t r u e Why the following is true? Run! 1 a l e r t ([ ' x ' ]= =' x ') Open solution Boolean context There is one more standard conversion in JavaScript.info/tutorial/object-conversion 3/5 . In the example below. there is no magic method. Instead. " 0 "is t r u ein JavaScript.1/21/2014 Conversion. Object may not implement such conversion on their own. there is a hardcoded table of conversions: Value t r u e / f a l s e u n d e f i n e d . like i f ( o b j ) .w h i l e ( o b j )etc.i ft r e a t s" \ n 0 \ n "a st r u e It is possible that a = =b . But now let’s see how the left part behaves in boolean context: Run! 1 i f( [ 0 ] )a l e r t ( 1 ) / /1 . called [ [ t o B o o l e a n ] ]in the specification. Funny things happen if we do. For example. The comparison always converts to primitive: Run! 1 2 3 4 5 6 7 8 v a ra={ v a l u e O f :f u n c t i o n ( ){r e t u r n 1} } v a rb ={ v a l u e O f :f u n c t i o n ( ){r e t u r n 0} } a l e r t (a>b) / /1>0 . others .i ft r e a t s[ 0 ]a st r u e 2 i f( " \ n 0 \ n " )a l e r t ( 2 )/ /2 . you may use double-negation: ! ! v a lor direct call B o o l e a n ( v a l ) . we never use n e wB o o l e a nfor any purpose. we have numeric conversion (equality does it): Run! 1 a l e r t ([ 0 ]= =0) / /t r u e 2 a l e r t (" \ n 0 \ n "= =0)/ /t r u e 3 a l e r t (" \ n 0 \ n "= =f a l s e)/ /t r u e So one may guess that [ 0 ]and " \ n 0 \ n "are falsy. any other .t r u e t r u e ' Unlike many programming languages (for example PHP).

2. 2011.1/21/2014 Conversion. Why they are equal? Run! 1 a l e r t ([ ]= =! [ ])/ /t r u e Open solution Figure out the result of expressions. 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 1 0 1 1 1 2 1 3 6/" 3 " " 2 "*" 3 " 4+5+" p x " " $ "+4+5 
 " 4 "-2 
 " 4 p x "-2 
 7/0 
 { } [ 0 ] 
 p a r s e I n t ( " 0 9 " ) 
 5& &2 
 2& &5 
 5| |0 
 0| |5 Open solution Summary There are three conversions in JavaScript. Actually.3 (equality comparison) and 9. especially 11.3 (toNumber).9. operators. But simple when you get it. ‹ Array Four scents of "this" › The content of this site is available under the terms of CC BY-NC-SA. "JavaScript™ is a registered trademark of Oracle corp. refer to the specification: ECMA-262 5th ed. 3. Boolean: converts according to the table. and 11. © Ilya Kantor. check against the solution. the conversion is a bit more sophisticated than described here. http://javascript. P. When you are done. and here any object is true… Wops! Java programmers’ eyes usually pop out when they see that.. which depend on the context: 1. The a l e r tconverts it to String. Numeric: maths.1 (toPrimitive) and 9.8. and it becomes " f a l s e " … Right.S.info/tutorial/object-conversion 4/5 . toString and valueOf | JavaScript Tutorial 1 a l e r t (n e wB o o l e a n ( f a l s e ))/ /f a l s e But… Run! 1 i f(n e wB o o l e a n ( f a l s e )){ 2 a l e r t ( t r u e )/ /t r u e 3 } That’s because n e wB o o l e a nis an object. That’s different from most other programmer languages.5 (relational comparison). uses v a l u e O f-> t o S t r i n g . String: output. For a maximally precise conversion algorithms. uses t o S t r i n g . But i fconverts it to boolean primitive. I’ve left out a good bit of complexity to concentrate on how it really works. This site is not affiliated with Oracle corp.

1/21/2014 Conversion.info/tutorial/object-conversion 5/5 . toString and valueOf | JavaScript Tutorial http://javascript.