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
How [ ] is converted to String in JavaScript?
In JavaScript, an empty array [] converts to an empty string "" when converted to a string. This happens through JavaScript's automatic type conversion or by using explicit conversion methods.
Using String() Method
The String() method explicitly converts any value to a string:
<!DOCTYPE html>
<html>
<body>
<p>Convert [] to String</p>
<script>
var myVal = [];
document.write("String: " + String(myVal));
document.write("<br>Type: " + typeof String(myVal));
</script>
</body>
</html>
String: Type: string
Using toString() Method
Arrays have a built-in toString() method that converts them to strings:
<!DOCTYPE html>
<html>
<body>
<script>
var emptyArray = [];
var arrayWithItems = [1, 2, 3];
document.write("Empty array: '" + emptyArray.toString() + "'<br>");
document.write("Array with items: '" + arrayWithItems.toString() + "'");
</script>
</body>
</html>
Empty array: '' Array with items: '1,2,3'
Automatic Type Conversion
JavaScript automatically converts arrays to strings when used in string contexts:
<!DOCTYPE html>
<html>
<body>
<script>
var arr = [];
document.write("Concatenation: '" + arr + "'<br>");
document.write("Template literal: '" + `${arr}` + "'");
</script>
</body>
</html>
Concatenation: '' Template literal: ''
Comparison of Methods
| Method | Result for [] | Works with null/undefined? |
|---|---|---|
String([]) |
"" |
Yes |
[].toString() |
"" |
No (throws error) |
[] + "" |
"" |
Yes |
Conclusion
An empty array [] converts to an empty string "" in JavaScript. Use String() for explicit conversion or rely on automatic conversion in string contexts.
Advertisements
