toString() vs String() vs JSON.stringify()
JavaScript String Conversion Guide
Understanding how JavaScript converts values to strings is one of those things that seems trivial… until it suddenly breaks your code at 2 AM. Let’s walk through the three most common approaches:
String().toString()JSON.stringify()
With examples, edge cases, visual diagrams, and a bit of humour to keep things civilised.
🧭 High-Level Mental Model
Think of string conversion as three different “translation services”:
VALUE → String() → "some string"
VALUE → toString() → "some string" (if allowed)
VALUE → JSON.stringify() → "JSON formatted string"But the behaviour differs depending on what you hand over.
1. String() – The Polite Universal Translator
String() is a global function that attempts to convert any value into a string.
Visual Diagram
ANY VALUE
│
▼
String(value)
│
▼
ALWAYS STRING ✅Even for the awkward guests:
null → "null"
undefined → "undefined"
object → "[object Object]" 😅Basic Examples
String(123) // "123"
String(true) // "true"
String(null) // "null"
String(undefined) // "undefined"Why it’s useful
String() is extremely forgiving. It doesn’t complain. It doesn’t judge. It just converts.
String([1, 2, 3]) // "1,2,3"
String({a: 1}) // "[object Object]"Humour Analogy
Think of String() as that overly polite friend:
You: “Here’s an undefined existential concept.”
String(): “Ah yes, good sir. I shall represent it as ‘undefined’. Lovely choice.”
2. .toString() – The Slightly Moody Method
.toString() is a method available on many objects and primitives.
Visual Diagram
VALUE
│
▼
value.toString()
│
├── if value exists → STRING ✅
│
└── if null/undefined → 💥 ERROR ❌More explicitly:
null.toString() → TypeError 🚨
undefined.toString() → TypeError 🚨Because JavaScript says:
“You can’t call methods on something that doesn’t exist.”
Basic Examples
(123).toString() // "123"
true.toString() // "true"
[1, 2, 3].toString() // "1,2,3"Humour Analogy
.toString() is like a skilled but dramatic actor:
You: “Please convert null.”
toString(): “I refuse. I cannot perform under these conditions.” 🎭
3. JSON.stringify() – The Structured Storyteller
JSON.stringify() converts values into JSON-formatted strings.
Visual Diagram
VALUE
│
▼
JSON.stringify(value)
│
├── JSON-safe → STRING ✅
│
└── Not JSON-safe → undefined 🤷♂️Where it shines ✨
Object → '{"key":"value"}' ✅
Array → '[1,2,3]' ✅Comparison with String():
{a:1}
│
├── String() → "[object Object]" 😬
└── JSON.stringify() → '{"a":1}' ✅Basic Examples
JSON.stringify(123) // "123"
JSON.stringify(true) // "true"
JSON.stringify("hello") // '"hello"'
JSON.stringify({a: 1}) // '{"a":1}'
JSON.stringify([1, 2, 3]) // '[1,2,3]'Interesting Edge Cases
undefined → undefined
function(){} → undefined
Symbol() → undefinedInside objects:
{x: undefined} → '{}' 🙈JavaScript basically says:
“If it’s not JSON-safe, I’m pretending it never existed.”
Humour Analogy
JSON.stringify() is like a meticulous librarian:
“If your data isn’t properly catalogued, it will not enter the archive.” 📚
🔬 Behaviour Comparison Diagram
INPUT: nullString(null) → "null" ✅
null.toString() → ERROR ❌
JSON.stringify(null) → "null" ✅INPUT: undefinedString(undefined) → "undefined" ✅
undefined.toString() → ERROR ❌
JSON.stringify(undefined) → undefined 🤷♂️INPUT: {a:1}String(obj) → "[object Object]" 😬
obj.toString() → "[object Object]" 😬
JSON.stringify(obj) → '{"a":1}' ✅Comparison Summary
FeatureString()toString()JSON.stringify()Works on null✅❌✅Works on undefined✅❌⚠️ returns undefinedObjects😬 “[object Object]”😬 same✅ Proper JSONArrays✅✅✅Throws errorsRarelyYes (null/undefined)Rarely
Practical Rule of Thumb
Use:
Get aditya khare’s stories in your inbox
Join Medium for free to get updates from this writer.
✅ String(value) → When you want safe, universal conversion
✅ value.toString() → When you are sure value exists
✅ JSON.stringify(value) → When dealing with objects / APIs / storage / debugging
🐛 Real‑World Bug Examples (The Painfully Relatable Section)
Because nothing explains JavaScript better than mistakes we’ve all made 😄
Bug 1 — The Mysterious “[object Object]” API Disaster
Scenario
You send data to an API:
const user = { name: "Aditya", role: "Developer" };
fetch("/api", {
method: "POST",
body: String(user)
});What you expected
{"name":"Aditya","role":"Developer"}What the server received 😬
[object Object]Why this happensString(object) → calls default object conversion → useless string
Correct fix ✅
body: JSON.stringify(user)Life lesson
If your backend starts crying, check your string conversions.
Bug 2 — The Crash That Only Happens Sometimes
Scenario
function logValue(value) {
console.log(value.toString());
}logValue(42); // Works ✅
logValue(null); // 💥 TypeError ❌Why this happens.toString() cannot run on null or undefined
Correct fix ✅
console.log(String(value));Life lessontoString() is confident… until reality hits.
Bug 3 — Debugging Confusion From JSON.stringify()
Scenario
const data = {
name: "Test",
handler: () => console.log("hi")
};console.log(JSON.stringify(data));Output 🤨
{"name":"Test"}Where did handler go? 🙈
Why this happens
Functions are not JSON‑safe → silently removed
Life lesson
JSON.stringify() is a neat freak.
Bug 4 — The Undefined Logging Paradox
Scenario
console.log(JSON.stringify(undefined));Output
undefinedDeveloper brain 🧠
“Wait… I asked for a string. Why is this not a string?”
Why this happens
Top‑level undefined → returns undefined (not a string)
Safer alternative ✅
console.log(String(undefined)); // "undefined"Bug 5 — Accidental String Conversion in UI
Scenario
const price = 100;
const tax = 20;const total = price + String(tax);Result 😱
"10020"Why this happens
Number + String → String concatenation
Correct fix ✅
const total = price + tax; // 120Life lesson
One stray String() can financially ruin your UI.
Final Thought
JavaScript string conversion is like social etiquette:
String()→ Polite and forgiving.toString()→ Skilled but temperamentalJSON.stringify()→ Structured and professional
Choose wisely depending on your audience… or your data 😄
JavaScript string conversion is like social etiquette:
String()→ Polite and forgiving.toString()→ Skilled but temperamentalJSON.stringify()→ Structured and professional
Choose wisely depending on your audience… or your data 😄





