There are some important differences between String(x)and x.toString()in JavaScript.
String(x)- Type Conversion Function
String() is a function that converts any value to a string:
String(123) // "123"
String(true) // "true"
String(null) // "null"
String(undefined) // "undefined"
String({}) // "[object Object]"
String([1, 2, 3]) // "1,2,3"
x.toString()- Object Method
toString() is a method that objects call on themselves:
(123).toString() // "123"
true.toString() // "true"
[1, 2, 3].toString() // "1,2,3"
Key Differences
1. Handling nulland undefined
// String() works fine
String(null) // "null"
String(undefined) // "undefined"
// toString() throws errors
null.toString() // TypeError: Cannot read properties of null
undefined.toString() // TypeError: Cannot read properties of undefined
2. Primitive Values
// Both work for primitives
String(42) // "42"
(42).toString() // "42"
// But need careful syntax for numbers
42.toString() // SyntaxError - dot is part of decimal
(42).toString() // "42" - correct
42..toString() // "42" - also works (weird but valid)
3. Custom Objects
class Person {
constructor(name) {
this.name = name;
}
toString() {
return `Person: ${this.name}`;
}
}
const john = new Person('John');
String(john) // "Person: John" - uses toString() if available
john.toString() // "Person: John"
When to Use Which?
Use String(x)when:
-
Value might be
nullorundefined -
You want safe, predictable conversion
-
Working with unknown/variable types
function safeToString(value) {
return String(value); // Always works
}
Use x.toString()when:
-
You know the value is not
null/undefined -
You want to use custom
toString()methods -
Working with specific object types
// Safe pattern with optional chaining
value?.toString() // Returns undefined instead of throwing error
Advanced Differences
Radix Parameter (Number to String)
// Only toString() supports radix
(10).toString(2) // "1010" - binary
(255).toString(16) // "ff" - hexadecimal
String(10) // "10" - no radix support
Symbol Conversion
const sym = Symbol('test');
String(sym) // "Symbol(test)" - works
sym.toString() // "Symbol(test)" - also works
// But template literals
`${sym}` // TypeError: Cannot convert a Symbol value to a string
Summary Table
|
Feature |
String(x) |
x.toString() |
|---|---|---|
|
|
✅ Works |
❌ Throws error |
|
Primitive values |
✅ Works |
✅ Works (careful syntax) |
|
Custom objects |
Uses object's toString() |
Uses object's toString() |
|
Radix parameter |
❌ No support |
✅ For numbers |
|
Safety |
✅ Very safe |
❌ Less safe |
Best Practice
Prefer String(x)for general use - it's safer and more predictable. Use x.toString()when you specifically need its features (like radix) or are certain about the value type.
// Good for most cases
const str = String(someVariable);
// When you need specific functionality
const binary = number.toString(2);
1293

被折叠的 条评论
为什么被折叠?



