Is There Any Use Value To Using The ToString Method On A String?

- 1 answer

I can't figure out how the toString method could possibly be of any use when used on a string. A string is already a string and by its very nature it returns the value of the string.


console.log("Hello"); // => "Hello"
console.log(typeof "Hello"); // => string

Seems exactly the same as this...

console.log("Hello".toString()); // => "Hello"
console.log(typeof "Hello".toString()); // => string

If toString converts something to a string and returns it's value as a string and a string is a string and returns the value of a string I can only conclude that this method is totally meaningless. Am I missing something?

Note: "What is the difference between string literals and String objects in JavaScript?" and "Is there any use value to using the toString method on a string?" are clearly not the same question so I don't think this should be considered a duplicate.



There might be a misunderstanding.

Strings are primitive values, that is, they are not object. And thus they don't have methods.

However, some primitive values can be wrapped in analogous objects. it's the case of booleans, numbers and strings.

When you attempt to use one of these primitive values as an object, e.g. calling a method, the following happens under the hood:

  1. An object wrapper (in this case, a string object) is created
  2. The property is read/written in that object
  3. No reference to that object is stored anywhere, and thus it's usually garbage collected

Therefore, yes, using toString method on a string primitive is usually useless, because it only converts it to an object string under the hood, and the method converts the string object back to a string primitive.

However, that's not the case when you have a string object, because you may want to convert it to a string primitive:

var obj = new String('hello');
typeof obj; // 'object'
var str = obj.toString();
typeof str; // 'string'

A case in which toString used on a string primitive is when you have replaced it with a custom function (not recommended):

String.prototype.toString = function() { return '[' + this + ']' };
'hello'.toString(); // "[hello]"