What is the difference between String(), toString(), and template literals for conversion?
Three ways to turn a value into a string.
String(value) — safest; works on anything, including null and undefined.
value.toString() — works on most values but throws on null or undefined.
Template literals — interpolate and convert in place; concise and readable.
Use String() when a value might be null/undefined; otherwise template literals are the cleanest.
// String() — safe for all values
console.log(String(42)); // '42'
console.log(String(null)); // 'null'
console.log(String(undefined)); // 'undefined'
console.log(String(true)); // 'true'
console.log(String([1,2,3])); // '1,2,3'
// .toString() — throws on null/undefined
console.log((42).toString()); // '42'
console.log((42).toString(2)); // '101010' (binary)
console.log((42).toString(16)); // '2a' (hex)
console.log(true.toString()); // 'true'
// null.toString(); // TypeError!
// undefined.toString(); // TypeError!
// Template literal — same as String()
console.log(`${42}`); // '42'
console.log(`${null}`); // 'null'
console.log(`${undefined}`); // 'undefined'
console.log(`Value: ${42}`); // 'Value: 42'String() is the safest — handles null and undefined. toString() throws on null/undefined but supports radix (binary, hex). Template literals use String() internally and are the most common in modern code. toString(2) for binary and toString(16) for hex are unique to .toString().
String() is safe for all values. toString() throws on null/undefined but has radix for number bases. Template literals are the modern standard.
The toString(2) for binary conversion is a practical detail.