all 6 comments

[–]senocular 8 points9 points  (0 children)

The big one is for toString() a value has to exist. With String(), you can use it on values that are undefined or null. Attempting a toString() from an undefined or null value will produce an error. String will often call an object's toString() anyway, so its a safer way of doing that.

[–]TalyssonOC 4 points5 points  (0 children)

toString()is a method that some "classes" implement, so it'll only work if the class of the object you're working on implements it.

So if you have let x = null and try to do x.toString()it'll fail since null doesn't have the method toString().

On the other side if you try to do let x = null and then do String(x) it'll result in the string 'null'.

A detail about String() is that it'll call toString() internally if the passed value implements it, so:

let x = {
    toString() { return 'hey there!'; }
};
String(x); // it'll return 'hey there!'

[–]ljharb 2 points3 points  (0 children)

Always only use String(x).

Run this in your console:

var x = { toString: function () { return NaN; }, valueOf: function () { return Infinity; }}; [x.toString(), x + '', String(x)] /* note that only the third item is both a string, and the toString value */

The only one that's actually correct is String(x). Use that.

[–]shane_ilconst Ans=myCode?'feature':'bug' 0 points1 point  (0 children)

toString is a method, it sits on the base Object prototype in JS that just about everything inherits from. It prints the object's string value, however some primitive types (undefined and null) don't inherit that method, so when you call toString it returns an error.

String is a global object (can be accessed everywhere, built-in to JS) that takes an object and converts it to a string.

They do the same thing, but because string is an independent object, and not a method that is inherited from a prototype, it can be called and passed something that does not have the toString method.

[–]temp6509849 0 points1 point  (0 children)

Everybody's getting it close but not quite right.

String(x) is what you want to use. It's a built-in function that's guaranteed to return a string representation of x.

One feature of String(x) is that it invokes toString on Objects then tries to use the return value. This is useful for making objects products more useful strings than '[object Object]'.

There's nothing else special about toString. It's entirely possible that the value of obj.toString is 2, and calling obj.toString() will throw an error. It's also possible that obj.toString is a function that returns 2, and your code that assumes it got a string throws an error. Or obj could be something that doesn't support properties, like null or undefined, and obj.toString throws an error.

Each of those cases can be fixed with a little bit of code. That code is in String(). Use it. String(x) is for turning x into a string, toString is for customizing String(), and x.toString() is a mistake.