How to convert values to boolean in JavaScript?
Converting a value to a boolean in JavaScript is quite simple and easy. We can convert any value to boolean in multiple ways.
Let us consider we have a variable called value and it has null in it.
const value = null;
Using double negation (!!)
console.log(!!value) // false
Using Boolean method:
console.log(Boolean(value)) // false
Convert string to Boolean
const value = 'null'; console.log(Boolean(value)) // true console.log(!!value) // true
Convert number to Boolean
const value = 20; console.log(Boolean(value)); // true console.log(!!value); // true
Convert falsy values to Boolean
!!false; // false !!undefined; // false !!null; // false !!NaN; // false !!0; // false !!''; // false
Boolean(false); // false Boolean(undefined); // false Boolean(null); // false Boolean(NaN); // false Boolean(0); // false Boolean(''); // false