As obvious and easy as it may sound, converting string values of "true" and "false" to booleans can be tricky. There are many ways to shoot our own foot, if you don’t know how JavaScript works under the hood.

Use JSON.parse to convert a string to boolean

You can use JSON.parse not only to parse JSON, but to also convert strings to booleans!

JSON.parse(s.toLowerCase());

Example:

const arr = ['true', 'false', 'TruE', 'FAlsE'];

for(let i = 0; i < arr.length; i++) {
  const converted = JSON.parse(arr[i].toLowerCase());
  console.log(converted, typeof converted);
}

The console output will show that we have correctly converted all the string in arr too boolean values.

true boolean
false boolean
true boolean
false boolean

Use a regular expression to convert a JS string to boolean

Here’s a regex that you can use to convert a string to boolean in JavaScript.

function stringToBoolean(s) {
  return /^\s*(true|1|on)\s*$/i.test(s);
}
const arr = ['true', 'false', 'TruE', 'FAlsE'];

for(let i = 0; i < arr.length; i++) {
  const converted = stringToBoolean(arr[i]);
  console.log(converted, typeof converted);
}

The result remains the same.

true boolean
false boolean
true boolean
false boolean