Skip to content

when to use toString() and valueOf()? #189

Answered by pero5ar
wjm1314 asked this question in WTF Questions
Discussion options

You must be logged in to vote

The join is actually perfectly expected. You're joining array elements into a string so it triggers toString for each element.

The + is also expected, although a bit less, the thing is that + is primarily an arithmetic operator so it triggers valueOf, however the valueOf 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.

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by denysdovhan
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants
Converted from issue

This discussion was converted from issue #89 on February 05, 2021 14:55.