How do I convert a string to a boolean in JavaScript without using eval()?
Rashid D
rashid d profile pic

To convert a string to a boolean value in JavaScript without usingeval(), you can use conditional statements or explicit comparisons. Here are a few approaches: 1. Using conditional statements: You can use conditional statements such as the ternary operator orif statement to convert a string to a boolean based on specific conditions. For example:

1
2
3
4
5
6
7
8

function stringToBoolean(str) {
  return str === 'true' ? true : false;
}

const strValue = 'true';
const booleanValue = stringToBoolean(strValue);
console.log(booleanValue); // Output: true

In this example, thestringToBoolean function compares the input string with the'true' literal and returnstrue if they match; otherwise, it returnsfalse. 2. Using explicit comparisons: You can use explicit comparisons to convert a string to a boolean. For example, you can use the=== operator to compare the string value with the truthy string'true'. Here's an example:

1
2
3
4
5
6
7
8

function stringToBoolean(str) {
  return str === 'true';
}

const strValue = 'true';
const booleanValue = stringToBoolean(strValue);
console.log(booleanValue); // Output: true

In this example, thestringToBoolean function directly returns the result of the=== comparison, which will betrue if the input string is equal to'true'. It's important to note that the above approaches assume that the input string is either'true' or'false'. If you expect other truthy or falsy string values, you can extend the comparison logic accordingly. Additionally, keep in mind that JavaScript has a built-in mechanism for type coercion, so simply usingBoolean() as a constructor with the string value can also convert it to a boolean. However, this approach treats any non-empty string astrue and an empty string asfalse. Here's an example:

1
2
3
4

const strValue = 'true';
const booleanValue = Boolean(strValue);
console.log(booleanValue); // Output: true

In this example, theBoolean() constructor is used to convert the string to a boolean value, resulting intrue since the string is non-empty. Choose the approach that suits your specific requirements and the expected input values.