JavaScript中类型转字符串:优先用String()还是模板字面量?含数字场景
Great question—this is one of those small details that can trip up developers until you dig into the subtle differences! Let’s break down when to use each, and what separates them beyond just readability.
First: Which to Prefer?
It depends on your intent:
- If your sole goal is to convert a value to a string (no interpolation or concatenation),
String()is more explicit. It screams, "I’m intentionally converting this value to a string"—no ambiguity. - If you’re embedding the value into a longer string (e.g.,
"The value is: " + n), template literals (${n}) are cleaner and more readable, so go with those.
For your specific example with const n = 3.14, both String(n) and ${n} will return "3.14"—the result is identical. Pick whichever aligns with your code’s style and intent.
Beyond Readability: Key Differences
While they behave the same for most common values (numbers, strings, null, undefined, plain objects), there are critical edge cases to know:
1. Symbol Handling
This is the biggest practical difference. Symbols cannot be implicitly converted to strings—so template literals will throw an error if you try to interpolate one:
const sym = Symbol('my-symbol'); String(sym); // Returns "Symbol(my-symbol)" (works fine, explicit conversion) `${sym}`; // Throws TypeError: Cannot convert a Symbol value to a string
If your variable might ever hold a Symbol, String() is the only safe choice.
2. Intent Clarity
As mentioned earlier, String() makes your purpose explicit. If you see String(n) in code, you immediately know the goal is type conversion. If you see ${n} out of context, it might look like part of a larger interpolation, even if it’s just converting a value. This can matter for maintainability—especially for other developers reading your code.
3. Performance (Negligible for Most Use Cases)
In microbenchmarks, String() can be slightly faster than template literals for single-value conversion. But modern JavaScript engines optimize both operations so well that you’ll never notice the difference in real-world apps. Don’t prioritize performance here—focus on readability and intent instead.
4. Behavior with Custom Objects
For objects with custom toString() or valueOf() methods, both approaches follow the same ToPrimitive abstract operation (with a "string" hint). This means they’ll produce the same result:
const customObj = { toString() { return 'custom string'; }, valueOf() { return 456; } }; String(customObj); // "custom string" `${customObj}`; // "custom string"
If toString() returns a non-primitive value, both will fall back to valueOf()—so no surprises here.
Final Recommendations
- Use
String()when you need explicit type conversion (especially if Symbols are a possibility). - Use template literals when you need string interpolation or concatenation—they’re far cleaner than string concatenation with
+.
内容的提问来源于stack exchange,提问作者Daniel O'Leary

