when to use toString() and valueOf()? #189
-
Example(Unexpected result):var foo = { |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
The The |
Beta Was this translation helpful? Give feedback.
-
oh~~~, I got it! Thank you! |
Beta Was this translation helpful? Give feedback.
The
join
is actually perfectly expected. You're joining array elements into a string so it triggerstoString
for each element.The
+
is also expected, although a bit less, the thing is that+
is primarily an arithmetic operator so it triggersvalueOf
, however thevalueOf
a string primitive is that string primitive and since one of the values in the expression remained a string the+
falls back to being a concatenation operator. This can be seen as a bit WTF, however situations similar to that are covered in the Funny math section.