Difference between String() and new String() in Javascript

Using the String() constructor without new gives you the string (primitive) value of the passed parameter. It’s like boxing the parameter in a native object if necessary (like a Number or Boolean), and then calling .toString() on it. (Of course if you pass a plain object reference it just calls .toString() on that.)

Calling new String(something) makes a String instance object.

The results look the same via console.log() because it’ll just extract the primitive string from the String instance you pass to it.

So: just plain String() returns a string primitive. new String(xyz) returns an object constructed by the String constructor.

It’s rarely necessary to explicitly construct a String instance.

Leave a Comment