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 to convert a boolean value to string value in JavaScript?
In JavaScript, there are several ways to convert a boolean value to a string. The most common methods include using the toString() method, string concatenation, and the String() constructor.
Using toString() Method
The toString() method converts a boolean value to its string representation ("true" or "false").
<html>
<head>
<title>Boolean to String Conversion</title>
</head>
<body>
<script>
var flag1 = true;
var flag2 = false;
document.write("flag1.toString(): " + flag1.toString() + "<br>");
document.write("flag2.toString(): " + flag2.toString());
</script>
</body>
</html>
flag1.toString(): true flag2.toString(): false
Using String() Constructor
The String() constructor provides another reliable way to convert boolean values to strings.
<html>
<head>
<title>String Constructor Method</title>
</head>
<body>
<script>
var boolTrue = true;
var boolFalse = false;
document.write("String(boolTrue): " + String(boolTrue) + "<br>");
document.write("String(boolFalse): " + String(boolFalse));
</script>
</body>
</html>
String(boolTrue): true String(boolFalse): false
Using String Concatenation
Adding an empty string to a boolean value automatically converts it to a string.
<html>
<head>
<title>String Concatenation Method</title>
</head>
<body>
<script>
var isActive = true;
var isComplete = false;
document.write("isActive + '': " + (isActive + '') + "<br>");
document.write("isComplete + '': " + (isComplete + ''));
</script>
</body>
</html>
isActive + '': true isComplete + '': false
Comparison of Methods
| Method | Syntax | Recommended? |
|---|---|---|
toString() |
bool.toString() |
Yes - explicit and clear |
String() |
String(bool) |
Yes - handles null/undefined |
| String concatenation | bool + '' |
Less preferred - implicit |
Conclusion
Use toString() for explicit conversion or String() constructor for safer handling of potentially undefined values. Both methods reliably convert boolean values to their string equivalents.
Advertisements
