On the call of toString and valueOf of js

Let"s take a look at a discussion on StackOverFlow. I don"t understand the first two answers. If you can understand them, I think the second answer seems to be a good one.
Link: https://stackoverflow.com/que.

Apr.07,2021

+ operator rules:

  1. elements on both sides call their own valueOf methods to get leftValue and rightValue
  2. leftValue or rightValue as long as one of them is a string , the two are concatenated as strings, (note here that the result of the first step valueOf)
  3. if neither leftValue nor rightValue is a string, they will be converted to number for calculation.

attached to the original question

var x = {toString: function() {return "foo"; },
         valueOf: function() {return 42; }};
window.console.log ("x="+x);  // x=42
window.console.log ("x="+x.toString()); //x=foo

"x =" .valueof () is "x =" and x.valueOf () is 42. Because "x =" is a string, 42 is also converted to a string concatenated with it.

Menu