JS: String Constructor

By Xah Lee. Date: . Last updated: .

purpose of the string constructor is to convert a value to a string primitive value or a string object. Or create a string primitive value.

new String(arg)

🟢 tip: if you want chars instead of code unit, use Array.from.

// convert a string primitive to a its wrapper object
const xx = new String("a🦋c");

console.log(xx);
// [String: "a🦋c"]

// show the property keys
console.log(Reflect.ownKeys(xx));
// [ "0", "1", "2", "3", "length" ]

// check each key in object
console.assert(xx[0] === "a");
console.assert(xx[1] === "🦋"[0]);
console.assert(xx[2] === "🦋"[1]);
console.assert(xx[3] === "c");

// result is not a true array
console.assert(Array.isArray(xx) === false);
String()

Return a empty string primitive.

const xx = String();

console.assert(xx === "");

// result is a primitive type
console.assert(typeof xx === "string");
String(arg)

Convert arg to string Primitive Value , return it.

// shows the result of String(x) for all possible kind of primitive values x

// undefined type
console.assert(String(undefined) === "undefined");

// null type
console.assert(String(null) === "null");

// boolean primitives
console.assert(String(true) === "true");
console.assert(String(false) === "false");

// number primitives
console.assert(String(0) === "0");
console.assert(String(+0) === "0");
console.assert(String(-0) === "0");
console.assert(String(12) === "12");
console.assert(String(12.3) === "12.3");

// number primitives NaN and Infinity
console.assert(String(NaN) === "NaN");
console.assert(String(Infinity) === "Infinity");

// symbol primitives
console.assert(String(Symbol()) === "Symbol()");
console.assert(String(Symbol("xyz")) === "Symbol(xyz)");

if argument is Object Type , 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.

// convert array to string
console.assert(
 String([3, 4, 5]) === "3,4,5",
);

// String(myArray) is the same as myArray.toString()
console.assert(
 String([3, 4, 5]) === [3, 4, 5].toString(),
);
// convert object to string
console.assert(
 String({ dog: 4 }) === "[object Object]",
);

// String(myObj) is the same as myObj.toString()
console.assert(
 String({ dog: 4 }) === { dog: 4 }.toString(),
);