The String toString() method

By

Learn how the JavaScript toString() method returns the primitive string representation of a String object, working just like the valueOf() method does.

~~~

toString() returns the primitive string value of a String object. If you have a string wrapped in an object, this method gives you back the plain string inside it:

const str = new String('Test')
str.toString() //'Test'

It’s the same as valueOf(). Both return the primitive string.

Why does this method exist?

JavaScript has two kinds of strings: primitives and String objects.

When you write 'Test', you get a primitive. When you write new String('Test'), you get an object that wraps the primitive.

You can see the difference with typeof:

const name = 'Flavio'
typeof name //'string'

const wrapped = new String('Flavio')
typeof wrapped //'object'

toString() unwraps the object and gives you the primitive back:

typeof wrapped.toString() //'string'

What happens on a string primitive?

You can call toString() on a primitive too. JavaScript temporarily wraps it in a String object behind the scenes, and you get the same string back:

'Rome'.toString() //'Rome'

Nothing changes. The method returns the string itself.

A pitfall with String objects

Here is the trap. Comparing a String object to a primitive with === returns false, because one is an object and the other is not:

const city = new String('Rome')
city === 'Rome' //false

Calling toString() first fixes the comparison:

city.toString() === 'Rome' //true

My advice is to avoid the problem entirely. Never create strings with new String(). Use string literals, and you’ll never need toString() to unwrap anything.

One more detail

This version of toString() belongs to strings. It only works when called on a string or a String object. Calling it on anything else throws a TypeError:

String.prototype.toString.call(42) //TypeError

That’s fine in practice, because every other type has its own toString(). Numbers have one that accepts a base, arrays have one that joins the items with commas, and so on. Each type knows how to represent itself as a string.

~~~

Related posts about js: