Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
What will happen when { } is converted to String in JavaScript?
In JavaScript, when an empty object {} is converted to a string, it becomes "[object Object]". This happens because JavaScript calls the object's toString() method during string conversion.
How Object to String Conversion Works
JavaScript follows these steps when converting an object to a string:
- First, it calls the object's
toString()method - For plain objects,
toString()returns"[object Object]" - This is the default string representation for all plain objects
Example: Converting Empty Object to String
<!DOCTYPE html>
<html>
<body>
<p>Convert {} to String</p>
<script>
var myVal = {};
document.write("String: " + String(myVal));
</script>
</body>
</html>
String: [object Object]
Different Ways to Convert Objects to String
<!DOCTYPE html>
<html>
<body>
<script>
var obj = {};
// Using String() method
document.write("String(): " + String(obj) + "<br>");
// Using toString() method
document.write("toString(): " + obj.toString() + "<br>");
// Using template literals
document.write("Template: " + `${obj}` + "<br>");
// Using concatenation
document.write("Concatenation: " + ("" + obj) + "<br>");
</script>
</body>
</html>
String(): [object Object] toString(): [object Object] Template: [object Object] Concatenation: [object Object]
Object with Properties
Even objects with properties convert to the same string representation:
<!DOCTYPE html>
<html>
<body>
<script>
var obj1 = {};
var obj2 = {name: "John", age: 30};
document.write("Empty object: " + String(obj1) + "<br>");
document.write("Object with properties: " + String(obj2) + "<br>");
</script>
</body>
</html>
Empty object: [object Object] Object with properties: [object Object]
Getting Meaningful String Representation
To get a meaningful string representation of an object, use JSON.stringify():
<!DOCTYPE html>
<html>
<body>
<script>
var obj1 = {};
var obj2 = {name: "John", age: 30};
document.write("Empty object JSON: " + JSON.stringify(obj1) + "<br>");
document.write("Object JSON: " + JSON.stringify(obj2) + "<br>");
</script>
</body>
</html>
Empty object JSON: {}
Object JSON: {"name":"John","age":30}
Conclusion
Converting {} to string in JavaScript always results in "[object Object]" regardless of the object's properties. Use JSON.stringify() for meaningful string representations of objects.
Advertisements
