denysdovhan / wtfjs

🤪 A list of funny and tricky JavaScript examples
http://bit.ly/wtfjavascript
Do What The F*ck You Want To Public License
34.97k stars 2.55k forks source link

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

Closed wjm1314 closed 5 years ago

wjm1314 commented 6 years ago

Example(Unexpected result):

var foo = { toString: function() { return 'foo'}, valueOf: function() { return 5} } console.log(foo + 'bar'); //5bar console.log([foo,'bar'].join('')); //foobar

pero5ar commented 6 years ago

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.

wjm1314 commented 5 years ago

oh~~~, I got it! Thank you!