cast string to boolean in javascript

To cast a string to a boolean in JavaScript, you can simply use the Boolean() function. The Boolean() function is a built-in function in JavaScript that returns the boolean value of a variable.

Here's an example:

index.tsx
const str1 = 'true';
const str2 = 'false';

const bool1 = Boolean(str1);
const bool2 = Boolean(str2);

console.log(bool1); // true
console.log(bool2); // false
160 chars
9 lines

In this example, we declare two variables str1 and str2 with the string values 'true' and 'false' respectively. We then use the Boolean() function to cast these strings to boolean values and store the results in variables bool1 and bool2. Finally, we log the boolean values to the console.

Note that the Boolean() function performs the following conversions:

  • The string 'false' is converted to false
  • Any other non-empty string is converted to true
  • The empty string '' is converted to false
  • The value null is converted to false
  • The value undefined is converted to false
  • The number 0 is converted to false
  • Any other non-zero number is converted to true
  • Any non-null object is converted to true

gistlibby LogSnag