0
0
JavascriptHow-ToBeginner · 2 min read

JavaScript How to Convert Boolean to String Easily

You can convert a boolean to a string in JavaScript by using String(booleanValue) or booleanValue.toString().
📋

Examples

Inputtrue
Output"true"
Inputfalse
Output"false"
InputBoolean(1 > 2)
Output"false"
🧠

How to Think About It

To convert a boolean to a string, think about turning the true or false value into text. JavaScript provides simple ways to do this by either calling a function that converts any value to a string or by using a method that booleans have to get their string form.
📐

Algorithm

1
Get the boolean value you want to convert.
2
Use a conversion method like calling String() with the boolean as argument or use the toString() method on the boolean.
3
Return the resulting string.
💻

Code

javascript
const boolValue = true;
const str1 = String(boolValue);
const str2 = boolValue.toString();
console.log(str1);
console.log(str2);
Output
"true" "true"
🔍

Dry Run

Let's trace converting true to string using String() and toString()

1

Start with boolean true

boolValue = true

2

Convert using String()

String(true) returns "true"

3

Convert using toString()

true.toString() returns "true"

StepOperationResult
1boolValue = truetrue
2String(boolValue)"true"
3boolValue.toString()"true"
💡

Why This Works

Step 1: Using String() function

The String() function converts any value to its string form, so passing a boolean returns "true" or "false" as text.

Step 2: Using toString() method

Booleans have a built-in toString() method that returns their string equivalent directly.

🔄

Alternative Approaches

Template literals
javascript
const boolValue = false;
const str = `${boolValue}`;
console.log(str);
Uses string interpolation to convert boolean to string; simple and readable but less explicit.
Concatenation with empty string
javascript
const boolValue = true;
const str = boolValue + '';
console.log(str);
Adds an empty string to boolean, forcing conversion; quick but less clear to beginners.

Complexity: O(1) time, O(1) space

Time Complexity

Conversion is a simple operation with no loops, so it runs in constant time.

Space Complexity

Only a small string is created to hold the result, so space usage is constant.

Which Approach is Fastest?

All methods (String(), toString(), template literals, concatenation) run in constant time and are very fast; choose based on readability.

ApproachTimeSpaceBest For
String()O(1)O(1)Clear and explicit conversion
toString()O(1)O(1)Object method, concise
Template literalsO(1)O(1)Readable string interpolation
ConcatenationO(1)O(1)Quick shorthand conversion
💡
Use String(booleanValue) for clear and explicit boolean to string conversion.
⚠️
Trying to convert boolean to string by just printing it without conversion, which may cause unexpected results in some contexts.