1
"J" + { toString: function() { return "S"; } }; // "JS"

Why is the output "JS?"

When I do:

 "J" + { someFoo: function() { return "S"; } }; // "J[object Object]"

Why isn't this also "JS"?

I'm trying to figure out how the .toString() is getting used inside the first block.

Thanks

2
  • 6
    toString is a special function (in object's prototype), which is called when a stringified mode of the object is required. In the former case you've overridden it to return S. In the latter case the native function returns the default value. Commented Feb 11, 2015 at 18:08
  • "Why does this work in JavaScript" is not a question people would search google for. Your question should reflect the actual problem you're facing -- what would you type into Google to find the answer? This does require you to know the parts of what you're searching for, which is why Stack Overflow shouldn't be your 0th place for learning. Commented Feb 11, 2015 at 18:09

1 Answer 1

4

toString is a special function (in object's prototype), which is called when a stringified mode of the object is required.

In your cases, the addition operator calls the toString method of the object. From the specs:

  1. If Type(lprim) is String or Type(rprim) is String, then

    a. Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim).

However, this native method can be overridden, which you've done* in the first snippet. Addition operator just calls the custom method, which produces the result you've got.

In the latter snippet toString just returns a default value for objects.

You can see this happening in many situations, for example alert({}) calls internal toString method from object's prototype, since alert requires a string as an argument.

(* More accurate: you haven't re-written the native property, rather you've created an own property to the object with the same name, which is used instead of searching the native property from the prototype chain.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.