JS: String Constructor

By Xah Lee. Date: . Last updated: .
new String(value)
const xstrObj = new String("a🦋c");
console.log(xstrObj);
// [String: "a🦋c"]

console.assert(xstrObj[0] === "a");
console.assert(xstrObj[1] === "🦋"[0]);
console.assert(xstrObj[2] === "🦋"[1]);
console.assert(xstrObj[3] === "c");

🛑 WARNING: if you want chars instead of code unit, use e.g. Array.from("a🦋c") .

String()

Return a empty string.

console.assert(String() === "");
String(value)

Convert value to string Primitive Value , return it.

// list of String(primitiveValue) for all possible primitiveValue

// 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({ "p": 4 }) === "[object Object]");

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

JavaScript. String