How to Convert JavaScript String to Boolean

The Boolean object is an object wrapper for a boolean value. Sometimes in our project, we may have a boolean value in string format (“true” or “false”), and we want its boolean equivalent (such as true or false). 

JavaScript String to Boolean

To convert String to Boolean in JavaScript, use the !! operator or Boolean() function. Any string which isn’t the empty string will evaluate to true by using them.

Syntax

Boolean(value);

# OR

!!value;

Example

Let’s convert string to boolean using !! operator.

let data = "Millie Bobby Brown"

let data_bool = !!data

console.log(typeof(data_bool))
console.log(data_bool)

Output

boolean
true

You can see that !! has converted a “Millie Bobby Brown” string into a boolean value true.

How the !! works

The first ! constrain the value to a boolean and inverse it. In this case, the ! MllieBobbyBrown will return false. So to reverse it back to true, we put another ! on it. Hence the double use !!.

const data = "Millie Bobby Brown"

!data // false

!!data // true

Checkout for true or false valued strings

If you encounter a string with a value like “true” or “false”, you need to be very careful because !! will cause a problem.

const dt = "false"
console.log(!!dt)
console.log(Boolean(dt))

Output

true
true

Although it says false, it’s actually a string.

Applying !! on falsy values

In JavaScript, there are 6 falsy values. If you convert any of these to a boolean, it will return false.

console.log(!!false)
console.log(!!undefined)
console.log(!!null)
console.log(!!NaN)
console.log(!!0)
console.log(!!'')

Output

false
false
false
false
false
false

Using Boolean() method

Let’s use the boolean() method to convert.

let data = "Millie Bobby Brown"

let data_bool = Boolean(data)

console.log(typeof(data_bool))
console.log(data_bool)

Output

boolean
true

Applying Boolean on falsy values

console.log(Boolean(false))
console.log(Boolean(undefined))
console.log(Boolean(null))
console.log(Boolean(NaN))
console.log(Boolean(0))
console.log(Boolean(''))

Output

false
false
false
false
false
false

That’s it for converting JavaScript string to a boolean value.

See also

Convert Array to String

Add array to array in JavaScript

JavaScript add to Object

Leave a Comment