JavaScript: String Constructor

By Xah Lee. Date: . Last updated: .
String()
Return a empty string, same as "".
String(value)
Convert value to string primitive value, return it.
new String(value)
Like String(value), but returns a string object.

Calling String() without new is used for converting values to string primitive values.

Converting Primitive Values to Primitive Strings

console.log( String () === "" ); // true

console.log( String( undefined) === "undefined" ); // true
console.log( String( null) === "null" );          // true

console.log( String( true) === "true" );   // true
console.log( String( false) === "false" ); // true

console.log( String (0) === "0" );      // true
console.log( String (+0) === "0" );      // true
console.log( String (-0) === "0" );      // true

console.log( String (12) === "12" );      // true
console.log( String (12.3) === "12.3" );  // true
console.log( String( NaN) === "NaN" ); // true
console.log( String( Infinity) === "Infinity" ); // true

console.log( String ( Symbol() ) === "Symbol()" ); // true
console.log( String ( Symbol("xyz") ) === "Symbol(xyz)" ); // true

Convert Object to String Primitive

// convert array to string
console.log( String([3,4,5]) === "3,4,5" ); // true
// convert object to string
console.log( String({"k":4}) === "[object Object]" ); // true

When String( obj) is called, and obj is type object, the result is the value of calling the function obj[Symbol.toPrimitive]() if this method exist, or obj.toString(), or obj.valueOf(), in that order.

// showing String(myArray) is the same as myArray.toString()

const ar = [3,4,5];

console.log( Reflect.has ( ar , Symbol.toPrimitive ) ); // false
console.log( Reflect.has ( ar , "toString" ) ); // true

console.log( String(ar) === ar.toString () ); // true
// showing String(myObj) is the same as myObj.toString()

const obj = {"p":4};

console.log( Reflect.has ( obj , Symbol.toPrimitive ) ); // false
console.log( Reflect.has ( obj , "toString" ) ); // true

console.log( String(obj) === obj.toString () ); // true

Create String Object

Calling new String() is same as String(), except that the returned value is a string object.

Note: new String() is rarely useful.

Here's the difference between String() and new String().

// difference between “String()” and “new String()”

let s0 = "xyz";

let s1 = String (s0);
let s2 = new String (s0);

console.log( typeof s1 === "string" ); // true
console.log( typeof s2 === "object" ); // true

When string is converted to object, each character becomes a property.

let xx = new String("abc") ;
console.log(typeof xx === "object"); // true
console.log(xx);  // [String: 'abc']
console.log( Reflect.ownKeys ( xx ) ); // [ '0', '1', '2', 'length' ]

ECMAScript 2015 §Text Processing#sec-string-constructor-string-value

JavaScript String

JS in Depth
XAH  BUY NOW

JS in Depth

JS Obj Ref

DOM


JS Obj Ref

String

prototype