JavaScript Program for Boolean to String Conversion
This JavaScript program is designed to convert a boolean value to its corresponding string representation. In JavaScript, boolean values can either be true or false. The goal is to create a function that takes a boolean input and returns a string representation of that boolean value (“true” for true, and “false” for false).
Below are the methods to for Boolean to String Conversion:
Table of Content
- Using Conditional (Ternary) Operator
- Using if…else Statement
Using Conditional (Ternary) Operator
In this approach, we use a conditional (ternary) operator to check if the boolean value is true or false and then return the corresponding string.
Example: The below example uses the Conditional (Ternary) Operator for Boolean to String Conversion in JavaScript.
Javascript
function booleanToString(bool) { return bool ? "true" : "false" ; } console.log(booleanToString( true )); console.log(booleanToString( false )); |
true false
Using if…else Statement
In this approach, we use an if…else statement to check whether the boolean value is true or false, then return the corresponding string.
Example: The below example uses the if-else statement for Boolean to String Conversion in JavaScript.
Javascript
function booleanToString(bool) { if (bool) { return "true" ; } else { return "false" ; } } // Example usage: console.log(booleanToString( true )); console.log(booleanToString( false )); |
true false